Categories
Python Answers

How to find overlapping matches with a regex with Python?

Spread the love

Sometimes, we want to find overlapping matches with a regex with Python.

In this article, we’ll look at how to find overlapping matches with a regex with Python.

How to find overlapping matches with a regex with Python?

To find overlapping matches with a regex with Python, we can use the re.finall method with the r'(?=(\w\w))' regex string.

We have (?=...) to add a lookahead assertion to let us find overlapping matches.

For instance, we write:

import re

matches = re.findall(r'(?=(\w\w))', 'hello')
print(matches)

We call re.findall with the regex string and the string we want to find the matches for.

Therefore, matches is:

['he', 'el', 'll', 'lo']

Conclusion

To find overlapping matches with a regex with Python, we can use the re.finall method with the r'(?=(\w\w))' regex string.

We have (?=...) to add a lookahead assertion to let us find overlapping matches.

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 *