Python regex not giving me any matches

Viewed 49

I'm trying to match numbers that have 5 digits using regex in python. This is my code:

 import re
 matchstring = "These are 10101 random numbers 34345."
 regex_string = r'(?<!\d)\d{5}(?!\d)'
 all_matches = re.findall(matchstring, regex_string) 

I have no idea why I get 0 matches when I should get 2. I've tried using this regex on 2 python validator sites and on both sites these work. Any idea why in my code I get an empty list?

3 Answers

Function re.findall accepts arguments in order: pattern, then string:

re.findall(regex_string, matchstring)
['10101', '34345']

You can try this:

import re
matchstring = "These are 10101 random numbers 34345."
final_numbers = [i for i in re.findall("\d+", matchstring) if len(i) == 5]

Output:

['10101', '34345']
import re
matchstring = "These are 10101 random numbers 34345."
regex_string = r"\b\d{5}\b"
re.findall(regex_string , matchstring) 

output:

['10101', '34345']
Related