Astrophe Astrophe - 2 months ago 6
Python Question

python 2.7 Regex for a range of numbers

What is the regular expression to return a number in the range 274-342 and the rest of the line until '\n'? Here is my attempt.

import re
text = '333get\n361donuts\n400chickenmcsandwich\n290this\n195foo\n301string'

match=re.findall(r'(27[4-9]|8[0-9]|9[0-9]|3[0-3]\d|4[0-2])(.*)', text)


The correct regex would return the following result:

[('333', 'get'), ('290', 'this'), ('301', 'string')]

Answer

You can use '(\d+)(.*)' and then filter the list:

import re
text = '333get\n361donuts\n400chickenmcsandwich\n290this\n195foo\n301string'
matches = re.findall(r'(\d+)(.*)', text)
matches = [ item for item in matches if int(item[0]) in range(274,342) ]
print(matches)
# should print : [('333', 'get'), ('290', 'this'), ('301', 'string')]
Comments