我似乎找不到一个线程在这一个,但它似乎应该是相当简单的东西。我试图使用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和打印错误。
3条答案
按热度按时间83qze16e1#
\d[0-99]
表示一个数字(\d
),后跟一个数字(0-9
)或9
。如果您在[0-99]
的数字范围之后,则需要使用类似于\b\d{1,2}\b
的内容。这将匹配任何由1位或2位数字组成的数值。k3fezbri2#
您可以通过重新排序数字测试来简化正则表达式,并在2位数的测试中使用
elif
而不是if
。仅当“100”测试失败时,才执行2位数测试。
对于
r"\d{1,2}"
(在Python 2中),使用原始字符串并不是绝对必要的,但是对于任何包含反斜杠的正则表达式使用原始字符串是一个好习惯,在Python 3中,你 * 必须 * 使用原始字符串,否则会得到:注意,在Python中,条件不需要括号,所以使用括号只会增加不必要的混乱。
正如dawg在评论中提到的,对“100”的测试可以严格到
re.search(r"\b100\b", line)
,但如果我们能保证只测试0 - 100范围内的整数百分比,那就不需要了。lskq00tm3#
0 - 99岁:
正则表达式
'(?<!\-)\b(\d\d|\d)\b'
匹配0-99这2个数字,但不匹配负数,如-9
Demo
100很容易:
'(?<!\-)\b100\b'
如果不想匹配浮点数:
\b(?<![-.])(\d\d|\d)(?!\.)\b
Demo