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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 17 views 0 copies

Python code

13 lines
Python 3.9+
import 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

stdout
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

  1. Use `re.finditer()` when you also need match positions, not just the strings
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.