Python正则表达式匹配特定单词 [英] Python regex to match a specific word
问题描述
我想匹配测试报告中的所有行,其中包含单词不好". 文字示例:
I want to match all lines in a test report, which contain words 'Not Ok'. Example line of text :
'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/进行工作,但输出没有任何结果.任何想法,可能有什么问题吗?测试了其他各种参数,例如.".和"^ Test",它们可以完美地工作.
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.
推荐答案
您应在此处使用re.search
而不是re.match
.
You should use re.search
here not re.match
.
来自re.match
上的文档:
如果要在字符串中的任意位置找到匹配项,请改用search().
If you want to locate a match anywhere in string, use search() instead.
如果您要查找确切的单词'Not Ok'
,请使用\b
单词边界,否则
如果您只是在寻找'Not Ok'
子字符串,请使用simple:if 'Not Ok' in string
.
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
.
>>> 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
这篇关于Python正则表达式匹配特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!