我希望匹配测试报告中的所有行,其中包含“Not Ok”字样。 示例文字行:
'Test result 1: Not Ok -31.08'
我试过了:
filter1 = re.compile("Not Ok")
for line in myfile:
if filter1.match(line):
print line
哪个应该按照http://rubular.com/工作,但我在输出中什么也得不到。任何想法,可能是什么错?测试了各种其他参数,比如“。”和“^测试”,完美的工作。
答案 0 :(得分:26)
您应该在re.search
使用re.match
。
来自re.match
上的docs:
如果要在字符串中的任何位置找到匹配项,请改用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
答案 1 :(得分:3)
你可以简单地使用,
if <keyword> in str:
print('Found keyword')
示例:
if 'Not Ok' in input_string:
print('Found string')
答案 2 :(得分:1)
在这种情况下,绝对不需要使用RegEx!只需使用:
s = 'Test result 1: Not Ok -31.08'
if s.find('Not Ok') > 0 :
print("Found!")
或已经提到:
if 'Not Ok' in s:
print("Found!")