Python RegEx · Examples
Practical Python

Python RegEx Examples

Short, runnable programs that show python regular expressions (regex) in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Regular Expressions (regex) lesson.

1Validate a username with fullmatch()

The rule: start with a lowercase letter, then 2–15 more lowercase letters, digits or underscores. fullmatch() makes sure nothing extra sneaks in.

Validate a username with fullmatch()
import re

def is_valid_username(name):
    return re.fullmatch(r"[a-z][a-z0-9_]{2,15}", name) is not None

for name in ["asha_k", "2cool", "bo", "maya.r", "data_wizard_42"]:
    print(f"{name:<16}{is_valid_username(name)}")
Expected outputasha_k          True
2cool           False
bo              False
maya.r          False
data_wizard_42  True

2findall() with two groups returns tuples

Each match becomes a tuple of (item, price). Note \$ and \.: the dollar sign and the dot are special in regex, so they are escaped.

findall() with two groups returns tuples
import re

receipt = "apple $1.20, bread $2.50, cheese $7.05"
pairs = re.findall(r"(\w+) \$(\d+\.\d{2})", receipt)
print(pairs)

total = sum(float(price) for item, price in pairs)
print("Total:", round(total, 2))
Expected output[('apple', '1.20'), ('bread', '2.50'), ('cheese', '7.05')]
Total: 10.75

3Split on several different separators

str.split() handles one fixed separator. When the separators vary, re.split() can describe all of them at once — including the spaces around them.

Split on several different separators
import re

raw = "apples, pears;bananas |  kiwis"
print(raw.split(","))
print(re.split(r"\s*[,;|]\s*", raw))
Expected output['apples', ' pears;bananas |  kiwis']
['apples', 'pears', 'bananas', 'kiwis']

4Ignore case and find positions

The re.IGNORECASE flag (short form re.I) makes letters match in any case. finditer() yields match objects, so you also get each match's position.

Ignore case and find positions
import re

text = "Python is fun. I love PYTHON. python 3.13 is out."
print(len(re.findall(r"python", text)))
print(len(re.findall(r"python", text, re.IGNORECASE)))

for m in re.finditer(r"python", text, re.I):
    print(m.start(), m.group())
Expected output1
3
0 Python
22 PYTHON
30 python

Practise next

Python Regular Expressions (regex) exercises → Back to the lesson

Python Strings examplesWorking with JSON in Python examplesPython CSV Files examples