Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 214
casper Avatar asked Jun 13 '13 14:06

casper


People also ask

How do I match a word in regex?

To run a “whole words only” search using a regular expression, simply place the word between two word boundaries, as we did with ‹ \bcat\b ›. The first ‹ \b › requires the ‹ c › to occur at the very start of the string, or after a nonword character.

How do I extract a specific pattern from a string in Python?

Use re.search() to extract a substring matching a regular expression pattern. Specify the regular expression pattern as the first parameter and the target string as the second parameter. \d matches a digit character, and + matches one or more repetitions of the preceding pattern.


3 Answers

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 Ok\b',strs).group(0)
'Not Ok'
>>> match = re.search(r'\bNot Ok\b',strs)
>>> if match:
...     print "Found"
... else:
...     print "Not Found"
...     
Found
like image 63
Ashwini Chaudhary Avatar answered Oct 12 '22 02:10

Ashwini Chaudhary


You could simply use,

if <keyword> in str:
    print('Found keyword')

Example:

if 'Not Ok' in input_string:
    print('Found string')
like image 44
Tej91 Avatar answered Oct 12 '22 03:10

Tej91


Absolutely no need to use RegEx in this case! 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!")
like image 40
not2qubit Avatar answered Oct 12 '22 03:10

not2qubit