我似乎找不到关于这个问题的线索,但它看起来应该很简单。我尝试使用正则表达式在输出中搜索一行数字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并打印出错误。
发布于 2015-04-14 22:28:16
这个:\d[0-99]
表示一个数字(\d
),后跟一个数字(0-9
)或9
。如果您需要的是[0-99]
的数值范围,则需要使用类似于\b\d{1,2}\b
的内容。这将匹配由1位或2位数字组成的任何数值。
发布于 2015-04-14 22:44:49
您可以通过重新排序您的数字测试来简化正则表达式,并在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中不需要用括号将条件括起来,因此使用它们只会增加不必要的混乱。
正如dawg在评论中提到的," 100“的测试可以严格到re.search(r"\b100\b", line)
,但如果我们可以保证我们只测试0-100范围内的整数百分比,那么就不需要这样做。
发布于 2015-04-14 22:39:00
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
100很简单:'(?<!\-)\b100\b'
如果你不想匹配浮点数:\b(?<![-.])(\d\d|\d)(?!\.)\b
https://stackoverflow.com/questions/29629962
复制相似问题