Question

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.

Was it helpful?

Solution

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]

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top