Python正则表达式匹配特定的单词

cas*_*per 10 python regex match

我想匹配测试报告中的所有行,其中包含"Not Ok"字样.示例文字行:

'Test result 1: Not Ok -31.08'
Run Code Online (Sandbox Code Playgroud)

我试过这个:

filter1 = re.compile("Not Ok")
for line in myfile:                                     
    if filter1.match(line): 
       print line
Run Code Online (Sandbox Code Playgroud)

这应该根据http://rubular.com/工作,但我没有得到输出.任何想法,可能是什么错?测试了各种其他参数,比如"." 和"^测试",完美的工作.

Ash*_*ary 26

你应该re.search在这里使用re.match.

文档re.match:

如果要在字符串中的任何位置找到匹配项,请改用search().

如果你正在寻找确切的单词'Not Ok'然后使用\b单词边界,否则如果你只是寻找一个子字符串'Not Ok'然后使用简单:if 'Not Ok' in string.

>>> strs = 'Test result 1: Not Ok -31.08'
>>> re.search(r'\bNot Ok\b',strs).group(0)
'Not Ok'
>>> match = re.search(r'\bNot Ok\b',strs)
>>> if match:
...     print "Found"
... else:
...     print "Not Found"
...     
Found
Run Code Online (Sandbox Code Playgroud)

  • @casper没有`\ b`它也将返回'True`这样的东西:''KNot Oke'`.`re.findall`返回所有非重叠匹配的列表,为了检查目的,`re.search`是最佳选择. (3认同)

Tej*_*j91 6

你可以简单地使用,

if <keyword> in str:
    print('Found keyword')
Run Code Online (Sandbox Code Playgroud)

例子:

if 'Not Ok' in input_string:
    print('Found string')
Run Code Online (Sandbox Code Playgroud)