我似乎找不到关于这个问题的线索,但它看起来应该很简单。我尝试使用正则表达式在输出中搜索一行数字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: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范围内的整数百分比,那么就不需要这样做。
https://stackoverflow.com/questions/29629962
复制相似问题