Title: Match Email Addresses
Slug: match_email_addresses
Summary: Match Email Addresses
Date: 2016-05-01 12:00
Category: Regex
Tags: Basics
Authors: Chris Albon

Based on: StackOverflow

Preliminaries


In [20]:
# Load regex package
import re

Create some text


In [40]:
# Create a variable containing a text string
text =  'My email is chris@hotmail.com, thanks! No, I am at bob@data.ninja.'

Apply regex


In [44]:
# Find all email addresses
re.findall(r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9]+', text)

# Explanation:
# This regex has three parts
# [a-zA-Z0-9_.+-]+ Matches a word (the username) of any length
# @[a-zA-Z0-9-]+  Matches a word (the domain name) of any length
# \.[a-zA-Z0-9-.]+ Matches a word (the TLD) of any length


Out[44]:
['chris@hotmail.com', 'bob@data.ninja']