[英]Python regex to match a specific word
I want to match all lines in a test report, which contain words 'Not Ok'. 我想匹配测试报告中的所有行,其中包含“Not Ok”字样。 Example line of text : 示例文字行:
'Test result 1: Not Ok -31.08'
I tried this: 我试过这个:
filter1 = re.compile("Not Ok")
for line in myfile:
if filter1.match(line):
print line
which should work according to http://rubular.com/ , but I get nothing at the output. 这应该根据http://rubular.com/工作,但我没有得到输出。 Any idea, what might be wrong? 任何想法,可能是什么错? Tested various other parameters, like "." 测试了各种其他参数,比如“。” and "^Test" , which work perfectly. 和“^测试”,完美的工作。
You should use re.search
here not re.match
. 你应该在这里使用re.search
而不是re.match
。
From the docs on re.match
: 来自re.match
上的文档 :
If you want to locate a match anywhere in string, use search() instead. 如果要在字符串中的任何位置找到匹配项,请改用search()。
If you're looking for the exact word 'Not Ok'
then use \\b
word boundaries, otherwise if you're only looking for a substring 'Not Ok'
then use simple : if 'Not Ok' in string
. 如果你正在寻找确切的单词'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
You could simply use, 你可以简单地使用,
if <keyword> in str:
print('Found keyword')
Example: 例:
if 'Not Ok' in input_string:
print('Found string')
Absolutely no need to use RegEx in this case! 在这种情况下绝对不需要使用RegEx! Just use: 只需使用:
s = 'Test result 1: Not Ok -31.08'
if s.find('Not Ok') > 0 :
print("Found!")
or as already mentioned: 或者如前所述:
if 'Not Ok' in s:
print("Found!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.