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/工作,但我没有得到输出。任何想法,可能是什么错?测试了各种其他参数,例如“。”和“^测试”,完美的工作。
2 个解决方案
#1
24
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',那么使用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
#2
1
You could simply use,
你可以简单地使用,
if <keyword> in str:
print('Found keyword')
Example:
例:
if 'Not Ok' in input_string:
print('Found string')
#1
24
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',那么使用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
#2
1
You could simply use,
你可以简单地使用,
if <keyword> in str:
print('Found keyword')
Example:
例:
if 'Not Ok' in input_string:
print('Found string')