Python正则表达式搜索数字范围

b5lpy0ml  于 2023-02-18  发布在  Python
关注(0)|答案(3)|浏览(141)

我似乎找不到一个线程在这一个,但它似乎应该是相当简单的东西。我试图使用regex搜索一行输出中的数字0-99,并做一个动作,但如果数字是100,那么它会做一个不同的动作。以下是我所尝试的(简化版本):

OUTPUT = #Some command that will store the output in variable OUTPUT
OUTPUT = OUTPUT.split('\n')
for line in OUTPUT:
    if (re.search(r"Rebuild status:  percentage_complete", line)): #searches for the line, regardless of number
        if (re.search("\d[0-99]", line)): #if any number between 0 and 99 is found
            print("error")
        if (re.search("100", line)): #if number 100 is found
            print("complete")

我试过这个,它仍然拿起100和打印错误。

83qze16e

83qze16e1#

\d[0-99]表示一个数字(\d),后跟一个数字(0-9)或9。如果您在[0-99]的数字范围之后,则需要使用类似于\b\d{1,2}\b的内容。这将匹配任何由1位或2位数字组成的数值。

k3fezbri

k3fezbri2#

您可以通过重新排序数字测试来简化正则表达式,并在2位数的测试中使用elif而不是if

for line in output:
    if re.search("Rebuild status:  percentage_complete", line): 
        if re.search("100", line):
            print "complete"
        elif re.search(r"\d{1,2}", line): 
            print "error"

仅当“100”测试失败时,才执行2位数测试。
对于r"\d{1,2}"(在Python 2中),使用原始字符串并不是绝对必要的,但是对于任何包含反斜杠的正则表达式使用原始字符串是一个好习惯,在Python 3中,你 * 必须 * 使用原始字符串,否则会得到:

DeprecationWarning: invalid escape sequence '\d'

注意,在Python中,条件不需要括号,所以使用括号只会增加不必要的混乱。
正如dawg在评论中提到的,对“100”的测试可以严格到re.search(r"\b100\b", line),但如果我们能保证只测试0 - 100范围内的整数百分比,那就不需要了。

lskq00tm

lskq00tm3#

0 - 99岁:

>>> s='\n'.join(["line {} text".format(i) for i in range(-2,101) ])
>>> import re
>>> re.findall(r'(?<!\-)\b(\d\d|\d)\b', s)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']

正则表达式'(?<!\-)\b(\d\d|\d)\b'匹配0-99这2个数字,但不匹配负数,如-9
Demo
100很容易:'(?<!\-)\b100\b'
如果不想匹配浮点数:\b(?<![-.])(\d\d|\d)(?!\.)\b
Demo

相关问题