문제

In a Python match pattern, how do I match a literal digit like 1 after a backreference by number like \1?

I tried the \g<1> syntax that is available in substitution patterns for this purpose, but it doesn't work in my match pattern.

I have a larger problem that I want to solve using a function that will perform the following somewhat unusual task. The task is to construct patterns dynamically so that each pattern will match digit sequences that have repeated digits in certain positions and specific digits in the remaining positions.

도움이 되었습니까?

해결책

I noticed that I don't need the \g<1> syntax. Instead I can use one of several techniques to separate the numeric backreference like \2 from the digit like 9 that follows it. Here are three such techniques:

  • a non-capturing group (?:\2)9
  • an otherwise unnecessary quantification by one \2{1}9
  • using an otherwise unnecessary character class to contain only the digit that follows the backreference \2[9]

다른 팁

Put the digit that you want to match literally in a character class \1[1] or a group \1(1) of its own so that the bracket or parentheses separates the digit from the backreference.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top