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

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'bisb', 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.