Python Regex: Extract Email from Text (Crash Course)

Searching "python regex extract email from text"? Here's a crash course on Python's re module — findall, groups, match vs search, greedy matching — with real patterns for emails, URLs, and log files.

If you searched for "python regex extract email from text", you probably have a blob of text — scraped pages, log files, a CSV column — and you need every email address out of it. Here's the whole answer up front: import re text = """Contact us at support@example.com or sales@my-shop.io. Not an email: user@@broken, @nodomain, plain text.""" email_pattern = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}") print(email_pattern.findall(text)) # ['support@example.com', 'sales@my-shop.io'] Three lines, and it works. But copy-pasting regex you don't understand is how you end up with a pattern that matches user@@broken or misses name+tag@gmail.com . This crash course teaches you the re module properly — findall , groups, match vs search , greedy vs non-greedy — using real patterns you'll actually reuse. What you'll learn re.compile and why raw strings matter findall vs finditer , and what capture groups change about the output The match vs search gotcha that confuses every beginner Greedy vs non-greedy quantifiers re.sub for find-and-replace Real patterns: extracting URLs and parsing log files Step 1 — Python re.compile tutorial: compile once, use often re.compile() turns a pattern string into a reusable pattern object. You *can* call re.findall(pattern, text) directly — Python caches and compiles behind the scenes — but compiling explicitly is faster when you reuse the pattern and makes your intent clear: import re text = "Call 555-0142 or 555-0199. The year was 2026." # Without compile: fine for one-offs print(re.findall(r"\d{3}-\d{4}", text)) # With compile: reuse the pattern object phone = re.compile(r"\d{3}-\d{4}") print(phone.findall(text)) print(phone.search(text).group()) Two conventions that matter: Always use raw…

Explore