iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python RegEx

Regular expressions live in the re module. Use them when patterns get past what str.find / replace can handle.

The basics

PYTHON
import re

text = 'Email Ada at ada@example.com or ada@old.org'

# All matches
print(re.findall(r'[\w.+-]+@[\w.-]+', text))

# First match
m = re.search(r'\d+', 'order #4242')
print(m.group())       # '4242'

# Replace
print(re.sub(r'\s+', '-', 'hello  world')) # 'hello-world'

The common atoms

AtomMatches
.Any char except newline.
\d \DDigit / non-digit.
\w \WWord char / non-word.
\s \SWhitespace / non.
^ $Start, end of line.
\bWord boundary.

Quantifiers

QuantifierMeans
*0 or more
+1 or more
?0 or 1
{n} / {n,m}Exactly / range

Groups & named captures

PYTHON
m = re.match(r'(?P<user>\w+)@(?P<host>[\w.]+)', 'ada@example.com')
print(m['user'])     # ada
print(m['host'])     # example.com

Compile if you'll reuse

PYTHON
EMAIL = re.compile(r'[\w.+-]+@[\w.-]+')
for line in lines:
    for email in EMAIL.findall(line):
        ...
Tip: Always write regex strings as raw strings (r'…'). Otherwise \b, \n, etc. get interpreted as Python escapes before reaching the regex engine.

Example

Example
import re
text = 'email: ada@example.com, fallback: ada@old.org'
for m in re.findall(r'[\w.+-]+@[\w.-]+', text):
    print(m)
Try it Yourself »

Exercise

Write a regex pattern as a raw string with this prefix.

pattern = '\w+'

Test yourself

Q1. Regex patterns should be written as…
Q2. \w matches…
Q3. For reused patterns, prefer…

Discussion

Loading…