Python Practice › String Programs › Program 105

Extract email addresses

EasyString Programs · 105 of 106

Write a Python program to extract all email addresses from a string.

Advertisement
Input
a paragraph with four email addresses
Output
['john@gmail.com', 'jay@lic.com', 'hari@facebook.com', 'mery@hotmail.com']

Approach

  1. A regex for “letters @ domain . extension”.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs