How to find all matches to a regular Expression in Python?

Estimated read time 2 min read

To find all matches to a regular expression in Python, you can use the re module. The re module provides various functions for working with regular expressions. Here’s an example of how to find all matches:

import re

text = "Hello, my name is John. My email address is john@example.com. Please contact me."

pattern = r'\b\w+@\w+\.\w+\b'  # Regular expression pattern to match email addresses

matches = re.findall(pattern, text)

print(matches)

In this example, we have a text that contains an email address. We define a regular expression pattern using a raw string r'\b\w+@\w+\.\w+\b' to match email addresses. This pattern matches one or more word characters (\w+), followed by the @ symbol, then one or more word characters, a dot, and one or more word characters again.

We use the re.findall() function to find all non-overlapping matches of the pattern in the text. The findall() function returns a list of all matches found.

Finally, we print the matches, which in this case is the email address:

['john@example.com']

The output shows the email address found in the text.

You can adjust the regular expression pattern (pattern) based on your specific matching requirements.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply