Categories
Python Answers

How to use a regular expression match a whole word with Python?

Spread the love

Sometimes, we want to use a regular expression match a whole word with Python.

In this article, we’ll look at how to use a regular expression match a whole word with Python.

How to use a regular expression match a whole word with Python?

To use a regular expression match a whole word with Python, we can use the re.search method with a regex to match a whole word.

For instance, we write:

import re

x = "this is a sample"
res = re.search(r'\bis\b', x)
print(res)

We call re.search with a regex that matches the word ‘is’.

\b indicates the word boundary.

The 2nd argument is the string that we’re searching for the matches for.

Therefore, res is <re.Match object; span=(5, 7), match='is'>.

Conclusion

To use a regular expression match a whole word with Python, we can use the re.search method with a regex to match a whole word.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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