Regular expressions (regex) describe text patterns — useful for validating input, finding data and replacing text.
re functions
re.search(p, text)— first match anywhere (orNone)re.fullmatch(p, text)— the whole text must match (best for validation)re.findall(p, text)— all matches as a listre.sub(p, repl, text)— replacere.split(p, text)re.compile(p)— reuse a pattern
Write patterns as raw strings: r"\d+".
Building blocks
| Pattern | Matches |
|---|---|
\d \w \s |
digit, word character, whitespace |
. |
any character |
[aeiou], [0-9], [^0-9] |
sets |
* + ? |
0+, 1+, 0 or 1 |
{10}, {2,4} |
exact count, range |
^ $ |
start, end |
( ) |
group (capture) |
| |
or |
Groups
m.group(1), or named groups (?P<year>\d{4}) → m["year"].
Flags
re.IGNORECASE, re.MULTILINE.
Keep regexes simple; for complex formats (HTML, emails in depth) use proper libraries.
Example
Example — Validate and extract
Python
import re
mobile = re.compile(r"[6-9]\d{9}")
for m in ["9876543210", "1234567890", "98765"]:
print(m, "valid" if mobile.fullmatch(m) else "invalid")
text = "Contact asha@agyanadda.com or ravi.k@example.in by 25-12-2026."
print(re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text))
date = re.search(r"(?P<d>\d{2})-(?P<m>\d{2})-(?P<y>\d{4})", text)
print(date["y"], date["m"], date["d"])
messy = "Learn Python at AgyanAdda"
print(re.sub(r"\s+", " ", messy))
print(re.sub(r"\d(?=\d{4})", "*", "9876543210"))
Output: 9876543210 valid, 1234567890 invalid, 98765 invalid; the two email addresses; 2026 12 25; "Learn Python at AgyanAdda"; and the masked number ******3210.