Python正则表达式匹配特定单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17090144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python regex to match a specific word
提问by casper
I want to match all lines in a test report, which contain words 'Not Ok'. Example line of text :
我想匹配测试报告中包含“Not Ok”字样的所有行。文本行示例:
'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. Any idea, what might be wrong? Tested various other parameters, like "." and "^Test" , which work perfectly.
这应该根据http://rubular.com/工作,但我在输出中一无所获。任何想法,可能有什么问题?测试了各种其他参数,如“。” 和 "^Test" ,它完美地工作。
采纳答案by Ashwini Chaudhary
You should use re.searchhere not re.match.
你应该re.search在这里使用not re.match。
From the docson 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 \bword 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'则使用 simple : 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
回答by Tej91
You could simply use,
你可以简单地使用,
if <keyword> in str:
print('Found keyword')
Example:
例子:
if 'Not Ok' in input_string:
print('Found string')
回答by not2qubit
Absolutely no need to use RegEx in this case! Just use:
在这种情况下绝对不需要使用 RegEx!只需使用:
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!")

