python中数值范围的正则表达式

2024-09-29 22:31:06 发布

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

我需要找到格式为“数字编号”的数字范围。数字应在0-3000范围内。所以我想出了这个正则表达式

match = re.search(r'^[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]-[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]',sentence)

当我运行程序时,我只想提取句子中的56-900,但程序提取了其他数字,如2016、CLP2012等。。我只想提取中间有“-”的数字。我的模式有什么问题。在


Tags: 程序research格式match模式数字sentence
3条回答

这段代码只提取一个真正的范围x-y和{}

sentence = 'test 69 example 55-66 example 77-44 example 999-3001 example'

for word in re.findall('\d+-\d+', sentence):
    l = word.split('-')
    if int(l[0])< int(l[1]) <= 3000:
        word

此示例的输出:

^{pr2}$

使用python包regex_engine为数值范围生成正则表达式

您可以使用pip安装这个包

pip install regex-engine

from regex_engine import generator

generate = generator()

regex = generate.numerical_range(0,3000)

print(regex)

^([0-9]|[2-8][0-9]|1[0-9]|9[0-9]|[2-8][0-9][0-9]|1[1-9][0-9]|10[0-9]|9[0-8][0-9]|99[0-9]|[2-2][0-9][0-9][0-9]|1[1-9][0-9][0-9]|10[1-9][0-9]|100[0-9]|300[0-0])$

还可以为浮点和负范围生成正则表达式

^{pr2}$

如果要匹配整数范围,则需要用r“\b”(字符串的开始/结束)来保护匹配项:

>>> import re

>>> text = "2016, CLP2012 56-900 3000-3000 4000-4000 123-123 0-0"
>>> re.findall(r"\b\d+-\d+\b", text)
['56-900', '3000-3000', '4000-4000', '123-123', '0-0']

如果只想匹配0到3000之间的整数,则需要更精确的正则表达式,如下所示:

^{pr2}$

相关问题 更多 >

    热门问题