Python Practice › String Programs › Program 105
Extract email addresses
Write a Python program to extract all email addresses from a string.
Input
a paragraph with four email addresses
Output
['john@gmail.com', 'jay@lic.com', 'hari@facebook.com', 'mery@hotmail.com']
Approach
- A regex for “letters @ domain . extension”.
Solution
import re text = """We have some employee whosjohn@gmail.comemail id's are randomly distributedjay@lic.comwe want to gethari@facebook.comall the emailmery@hotmail.comid's from this given string."""print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))Output
['john@gmail.com', 'jay@lic.com', 'hari@facebook.com', 'mery@hotmail.com']
Line by line
Line 11
The pattern matches the name, “@”, a domain and at least one dot-separated extension.
Learn the concept
New to this topic? Read the lesson, then come back.