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

时间:2015-04-14 14:25:29

标签: python regex search

我似乎无法在这个上找到一个线程,但它似乎应该非常简单。我试图使用正则表达式在输出中搜索数字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并打印错误。

3 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:3)

您可以通过重新订购号码测试来简化您的正则表达式,并使用elif代替if进行2位数字的测试。

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中的条件不需要括号,因此使用它们只会增加不必要的混乱。


正如dawg在评论中提到的那样,“100”的测试可以收紧到re.search(r"\b100\b", line),但如果我们可以保证我们只测试0到100范围内的整数百分比,那就不需要了。 / p>

答案 2 :(得分:0)

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'匹配2位数字0-99并且不匹配负数,例如-9

Demo

100很简单:'(?<!\-)\b100\b'

如果您不想匹配浮点数:\b(?<![-.])(\d\d|\d)(?!\.)\b

Demo