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

bla*_*eon 5 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"
Run Code Online (Sandbox Code Playgroud)

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

npi*_*nti 5

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

  • @bladexeon:问题是'100`在技术上是一个正则表达式的有效匹配(它匹配'10`的值).我修改了表达式以包含单词边界(`\ b`)以应对这种情况. (3认同)