Python re Regular Expression for repeated, but not necessarily sequential digits

Question:

I want an RE that looks something like

'5[0-9]2[0-9]5'

But I need the two [0-9] wildcards to match.

So '50205', '51215', '52225', etc should all match but ‘51265’ and ‘53285’ should not.

Is there a way to do this?

I can use a loop like this

    a = '5d2d5'
    b = '51215'
    def match(a, b)
      for d in range(10):
        triala = a.replace('d',str(d))
        if triala == b: return True
      return False

I just wondered if there might be a built-in RE for something like this.

Asked By: Glen Hamblin

||

Answers:

Use backreference:

5             #
(?P<m>d)     # Capturing group named 'm' consisting of a digit
2             #
(?P=m)        # Whatever we matched in the 'm' group
5             #

Another trick you can use:

5(d)2(?:1)5

Try it on regex101.com.

Answered By: InSync
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.