python 2.7一系列数字的正则表达式

时间:2016-07-31 22:29:32

标签: python regex

什么是正则表达式返回274-342范围内的数字以及直到'\ n'的行的其余部分?这是我的尝试。

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)

正确的正则表达式将返回以下结果:

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

1 个答案:

答案 0 :(得分:1)

您可以使用'(\d+)(.*)'然后过滤列表:

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')]