Regular expressions · 2 / 15 Theory

Character classes and quantifiers

A pattern is built by combining two kinds of pieces: which character to look for (classes) and how many times (quantifiers).

Character classes

PatternMatches
\dA digit (0-9)
\wA letter, digit or underscore
\sA space, tab or newline
.Any character (except newline)
[abc]One of the letters a, b or c
[a-z]A lower-case letter from a to z
[^0-9]Any character that is NOT a digit

Capital letters invert the meaning: \D is "not a digit", \W "not alphanumeric", \S "not a space".

import re

print(re.findall(r"[aeiou]", "python"))   # ['o']
print(re.findall(r"[^aeiou]", "casa"))    # ['c', 's']

Quantifiers

PatternMeans
*Zero or more times
+One or more times
?Zero or one time (optional)
{n}Exactly n times
{n,m}Between n and m times
{n,}n or more times
import re

print(bool(re.fullmatch(r"\d{5}", "28001")))      # True
print(bool(re.fullmatch(r"\d{5}", "2800")))       # False
print(bool(re.fullmatch(r"colou?r", "color")))     # True
print(bool(re.fullmatch(r"colou?r", "colour")))    # True

Greedy by default

Quantifiers are greedy: they take as much as they can. Adding ? after them makes them lazy, so they take the minimum:

import re

text = "<b>one</b> and <b>two</b>"

print(re.findall(r"<b>.+</b>", text))    # ['<b>one</b> and <b>two</b>']
print(re.findall(r"<b>.+?</b>", text))   # ['<b>one</b>', '<b>two</b>']

Special characters

Some symbols have a special meaning: . * + ? ( ) [ ] { } | ^ $ \. To look for them literally, escape them with a backslash:

import re

print(re.findall(r"\d+\.\d+", "pi is 3.14"))      # ['3.14']
print(re.findall(r"\+34", "call +34 600"))        # ['+34']

Practice with Phone numbers and Validate emails.