Skip to content

Python regex match word in the string | Example code

  • by

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

From the docs on re.match:

Python regex matches a 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 is 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 the 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 or suggestions on this Python regex topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

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