Python regex match word in the string | Example code

To get the regex match word in the string use re.search here not re.match method in Python.

From the docs on re.match:

Python regex match word in a string example

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

If the search for the exact word ‘Not Ok’ then use \b word boundaries, otherwise only looking for a substring ‘Not Ok’ then use simply: if 'Not Ok' in string.

For this example, you have to import the re module.

import re

strs = 'Test result 1: Not Ok -31.08'
res = re.search(r'\bNot Ok\b', strs).group(0)

print(res)

Output:

Python regex match word in the string

Using if condition with the same example

import re

strs = 'Test result 1: Not Ok -31.08'

match = re.search(r'\bNot Ok\b', strs)
if match:
    print("Found")
else:
    print("Not Found")

Output:

Found

Do comment if you have any doubts and suggestions on this Python regex topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.