Python2.7正则表达式,用于一系列数字

2024-04-26 08:04:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: textimportregetstringmatch数字this
1条回答
网友
1楼 · 发布于 2024-04-26 08:04:01

您可以使用'(\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')]

相关问题 更多 >