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
| Atom | Matches |
|---|---|
. | Any char except newline. |
\d \D | Digit / non-digit. |
\w \W | Word char / non-word. |
\s \S | Whitespace / non. |
^ $ | Start, end of line. |
\b | Word boundary. |
Quantifiers
| Quantifier | Means |
|---|---|
* | 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+'
A single letter prefix.
Discussion
Loading…