agyanadda@gmail.com

Python Regular Expressions

Advanced Python 1 min read Updated Dec 4, 2026 Topic 29 of 32

Regular expressions (regex) describe text patterns — useful for validating input, finding data and replacing text.

re functions

  • re.search(p, text) — first match anywhere (or None)
  • re.fullmatch(p, text) — the whole text must match (best for validation)
  • re.findall(p, text) — all matches as a list
  • re.sub(p, repl, text) — replace
  • re.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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function checks that the WHOLE string matches?

Exercise 2 True / False

\d matches any digit.

Exercise 3 Fill in the Blank

Replace matches with re.___(pattern, replacement, text)

Frequently Asked Questions

Regex uses many backslashes. In normal strings Python also treats backslashes as escapes (\n, \t), which can break the pattern. Raw strings pass backslashes through unchanged.