Python regex to match a specific word

Python regex to match a specific word

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 youre looking for the exact word Not Ok then use b word boundaries, otherwise
if youre 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(rbNot Okb,strs).group(0)
Not Ok
>>> match = re.search(rbNot 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)

Python regex to match a specific word

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!)

Leave a Reply

Your email address will not be published. Required fields are marked *