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'

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.


You should use re.search here not re.match .

From the docs on re.match :

If you want to locate a match anywhere in string, use search() instead.

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 Okb',strs).group(0)
'Not Ok'
>>> match = re.search(r'bNot Okb',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')
链接地址: http://www.djcxy.com/p/13452.html

上一篇: 正则表达式来匹配没有前面字符串的字符串

下一篇: Python正则表达式匹配一个特定的单词