Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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             #

Try it on regex101.com.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading