Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

I have a test report and in that report, I just need to match all the lines which contain "Not Ok" words. See, let this be the example line of the text:

'Test result 1: Not Ok -31.08'

Now when I tried giving,

filter1 = re.compile("Not Ok")

for line in myfile:                                     

    if filter1.match(line): 

       print line

I didn't get any output. Can anyone tell me, what went wrong in the above code?

1 Answer

0 votes
by (26.4k points)
edited by

In your code, you have to make a few changes

You have to replace re.match with re.search

The reason is, search() helps you to locate a match anywhere in a string

If you want the exact word 'Not Ok' then you can use \b word boundaries, else if you want a substring 'Not ok', then you can simply use,

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

Want to be a Python expert? You can join this Python online course.

If you want to know more about this topic, you can also look at the following video tutorial :

Related questions

0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.6k points)
0 votes
2 answers
asked Sep 12, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...