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.
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.
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.
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.