Extract Email-Like Tokens from Text in Python
Uses a regular expression to find all email-like tokens in a string, returning them as a list with re.findall.
Python code
13 linesimport re
def extract_email_like_tokens(text):
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
return re.findall(pattern, text)
if __name__ == "__main__":
sample_text = (
"Contact us at support@example.com or sales@company.co.uk. "
"Invalid: hello@world, user@.com, test@domain."
)
tokens = extract_email_like_tokens(sample_text)
print("Found tokens:", tokens)
Output
Found tokens: ['support@example.com', 'sales@company.co.uk']
How it works
The pattern \b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b matches a username before the @, a domain after it, and a top-level domain of at least two letters. The \b word boundaries prevent partial matches inside longer strings. re.findall() scans the entire text and returns every non-overlapping match as a list. This expression is intentionally pragmatic—it accepts common email forms while rejecting obvious invalid ones like missing dots or TLDs.
Common mistakes
- Using `re.match()` or `re.search()` instead of `re.findall()`, which returns only one match
- Omitting `\b` boundaries so matches appear inside URLs or other words
- Allowing single-letter TLDs by ending the pattern with `[a-z]+` instead of `{2,}`
Variations
- Use `re.finditer()` when you also need match positions, not just the strings
- Compile the pattern once with `re.compile()` if you call the function in a loop
Real-world use cases
- Extracting customer contact emails from unstructured support ticket text.
- Scanning raw log files to collect sender addresses for analysis.
- Parsing scraped web pages to collect email contacts for outreach.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.