find email addresses in a string using regex in python

One way to find email addresses in a string using regex in Python is to use the re module. Here's an example:

main.py
import re

text = "Please contact john@example.com for more information. You can also reach us at info@company.com."

# Define a pattern to match email addresses
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

# Find all matches of the pattern in the text
matches = re.findall(pattern, text)

# Print the matches
print(matches)
346 chars
13 lines

Output:

main.py
['john@example.com', 'info@company.com']
41 chars
2 lines

In this example, the regex pattern matches email addresses that start with one or more alphanumeric characters, followed by "@" symbol, then one or more alphanumeric characters and periods, followed by a top-level domain name of two or more letters.

This technique is useful for data cleansing and validation, such as when extracting email addresses from text fields in a database.

gistlibby LogSnag