Introduction & Syntax
Regular Expressions · Study material
A regular expression (regex) is a tiny pattern language for text: "a 10-digit number starting with 6–9", "everything between < and >", "a date like 30-11-2026". With Python's re module one line can validate a phone number, pull every email out of a page, reformat dates or parse a log file. Regex questions appear in coding rounds and are everywhere in data cleaning, scraping and backend work. This topic covers the functions, the syntax, groups, greedy vs lazy matching and lookaheads, then gives you 50 practice questions run on Python 3.
On this page
- The re functions: search, match, fullmatch, findall, finditer, sub, split
- Character classes and quantifiers
- Greedy versus lazy matching
- Anchors, word boundaries and flags
- Groups, named groups and backreferences
- Escaping, raw strings and lookahead
The re functions
| Function | Returns |
|---|---|
re.search(p, s) | the first match anywhere, as a Match object, or None |
re.match(p, s) | a match only at the start of s |
re.fullmatch(p, s) | a match only if the whole string matches – best for validation |
re.findall(p, s) | a list of all matching strings (or of groups) |
re.finditer(p, s) | an iterator of Match objects |
re.sub(p, repl, s) | a new string with matches replaced |
re.split(p, s) | a list of the pieces between matches |
re.compile(p) | a reusable Pattern object with the same methods |
Always write patterns as raw strings (r"\d+") so that backslashes reach the regex engine unchanged. A Match object gives .group(), .start(), .end() and .span(); check for None before using it.
import re
text = "Order 4521 shipped on 2026-11-30, invoice 88"
m = re.search(r"\d+", text) # first match anywhere → a Match object (or None)
print(m.group(), m.start(), m.end())
print(re.match(r"\d+", text)) # match: only at the START of the string
print(bool(re.fullmatch(r"\d{4}", "4521"))) # fullmatch: the WHOLE string must match
print(re.findall(r"\d+", text)) # all matches as a list of strings
print([m.group() for m in re.finditer(r"\d{4}", text)]) # Match objects, one by one
print(re.sub(r"\d", "#", "PIN 4521")) # replace
print(re.split(r"[,\s]+", "a, b c,d")) # split on a pattern
4521 6 10 None True ['4521', '2026', '11', '30', '88'] ['4521', '2026'] PIN #### ['a', 'b', 'c', 'd']
Character classes and quantifiers
| Token | Matches | Token | Means |
|---|---|---|---|
. | any character except newline | * | 0 or more |
\d / \D | digit / non-digit | + | 1 or more |
\w / \W | word character (letter, digit, _) / not | ? | 0 or 1 (optional) |
\s / \S | whitespace / not | {n}, {m,n} | exactly n, between m and n |
[aeiou], [A-Z0-9] | one character from the set | a|b | a or b |
[^0-9] | one character NOT in the set | ( … ) | group |
import re
s = "Asha_21 paid Rs.4,500 on 30/11 at 9:05am!"
print(re.findall(r"\d", s)[:5]) # \d a digit
print(re.findall(r"\w+", s)[:4]) # \w letter, digit or underscore; + one or more
print(re.findall(r"[A-Z]\w*", s)) # [A-Z] one character from a set
print(re.findall(r"[^\w\s]", s)) # [^…] any character NOT in the set
print(re.findall(r"\d{1,2}/\d{2}", s)) # {m,n} between m and n times
print(re.findall(r"colou?r", "color colour colouur")) # ? optional (0 or 1)
['2', '1', '4', '5', '0'] ['Asha_21', 'paid', 'Rs', '4'] ['Asha_21', 'Rs'] ['.', ',', '/', ':', '!'] ['30/11'] ['color', 'colour']
Greedy versus lazy
Quantifiers are greedy: .+ grabs as much text as it can while still allowing a match, so <.+> spans from the first < to the last >. Adding ? (+?, *?, ??) makes them lazy: as little as possible. When a pattern contains groups, findall returns the groups instead of the whole match.
import re
html = "<b>Python</b> and <i>regex</i>"
print(re.findall(r"<.+>", html)) # greedy: as MUCH as possible
print(re.findall(r"<.+?>", html)) # lazy (?): as LITTLE as possible
print(re.findall(r"<(\w+)>", html)) # with a group: only the group is returned
print(re.sub(r"<.+?>", "", html)) # strip the tags
['<b>Python</b> and <i>regex</i>'] ['<b>', '</b>', '<i>', '</i>'] ['b', 'i'] Python and regex
Anchors, boundaries and flags
^ and $ anchor to the start and end of the string – or of every line with re.MULTILINE. \b is a word boundary, so \bcat\b matches "cat" but not "concatenate". Flags change how matching works: re.IGNORECASE (re.I), re.MULTILINE (re.M), re.DOTALL (. also matches newlines) and re.VERBOSE (re.X, which allows spaces and comments in long patterns). Combine them with |.
import re
log = """INFO server started
error disk full
ERROR db timeout"""
print(re.findall(r"^\w+", log)) # ^ start of the string only
print(re.findall(r"^\w+", log, re.MULTILINE)) # ^ start of EVERY line
print(re.findall(r"^error.*$", log, re.M | re.I)) # combine flags with |
print(bool(re.search(r"\bcat\b", "concatenate")), bool(re.search(r"\bcat\b", "a cat sat"))) # \b word boundary
pattern = re.compile(r"""
(\d{3}) # area code
[-\s]? # optional separator
(\d{4}) # number
""", re.VERBOSE) # VERBOSE: spaces and comments allowed
print(pattern.findall("call 044-2345 or 080 9876"))
['INFO']
['INFO', 'error', 'ERROR']
['error disk full', 'ERROR db timeout']
False True
[('044', '2345'), ('080', '9876')]Groups, named groups and backreferences
Brackets capture parts of a match: m.group(1), m.groups(). Named groups (?P<name>…) are read with m["name"] or m.groupdict(). In re.sub the replacement can refer to groups with \1 or \g<name>, which makes reformatting easy. (?:…) groups without capturing.
import re
m = re.search(r"(\w+)@(\w+)\.(com|in)", "Mail asha@learnfrenzy.in today")
print(m.group(0), m.group(1), m.group(2), m.groups())
date = re.search(r"(?P<day>\d{2})-(?P<month>\d{2})-(?P<year>\d{4})", "Due: 05-12-2026")
print(date["year"], date.groupdict())
# Backreferences in the replacement: \1, \2 … or \g<name>
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "2026-11-30"))
print(re.sub(r"(?P<first>\w+) (?P<last>\w+)", r"\g<last>, \g<first>", "Asha Rao"))
print(re.findall(r"(\w+)=(\d+)", "x=1 y=22 z=333")) # several groups → list of tuples
asha@learnfrenzy.in asha learnfrenzy ('asha', 'learnfrenzy', 'in')
2026 {'day': '05', 'month': '12', 'year': '2026'}
30/11/2026
Rao, Asha
[('x', '1'), ('y', '22'), ('z', '333')]Escaping special characters
The characters . ^ $ * + ? { } [ ] \ | ( ) have special meanings; escape them with a backslash to match them literally (\. for a dot). re.escape() escapes arbitrary text such as user input. Forgetting the r prefix is a classic bug: in a normal string "\b" is a backspace character, not a word boundary. re.sub also accepts a function that receives each Match and returns the replacement.
import re
print(re.findall(r"\d+\.\d+", "v1.2, 3x4, 10.05")) # \. a literal dot
print(re.findall(r"\d+.\d+", "v1.2, 3x4, 10.05")) # . ANY character – 3x4 matches too
print(re.escape("price (Rs.) * 2")) # escape user text before using it in a pattern
print(len("\b"), len(r"\b")) # "\b" is a backspace; r"\b" is backslash + b
# A function as the replacement
print(re.sub(r"\d+", lambda m: str(int(m.group()) * 2), "3 pens, 10 books"))
['1.2', '10.05'] ['1.2', '3x4', '10.05'] price\ \(Rs\.\)\ \*\ 2 1 2 6 pens, 20 books
Lookahead and lookbehind
(?=…) checks that something follows without consuming it, (?!…) that it does not; (?<=…) and (?<!…) look behind. Several lookaheads at the start of a pattern test several conditions in any order – the classic strong-password check.
import re
strong = re.compile(r"(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@#$%!]).{8,}") # each (?=…) checks without consuming
for pw in ["password", "Passw0rd", "Pass@w0rd", "P@1a"]:
print(f"{pw:<10} {'strong' if strong.fullmatch(pw) else 'weak'}")
print(re.findall(r"\d+(?= rupees)", "10 dollars, 250 rupees, 40 rupees")) # followed by
print(re.findall(r"(?<!-)\b\d+\b", "5 -3 12 -40 7")) # not preceded by -
password weak Passw0rd weak Pass@w0rd strong P@1a weak ['250', '40'] ['5', '12', '7']
Common mistakes
- Calling .group() on None – check the match first.
- Forgetting the r prefix – "\b" becomes a backspace.
- Using match() when search() is meant – match only looks at the start.
- Validating with search() and no anchors – "1234567" contains a 6-digit pin.
- An unescaped dot – matches any character.
- Greedy .* swallowing too much – use .*? or a negated class like [^>]*.
- findall with a group – returns only the group; use (?:…) for grouping without capturing.
Key points to remember
- Use raw strings for patterns.
- search finds anywhere, match at the start, fullmatch the whole string.
- findall returns strings (or group tuples); finditer returns Match objects.
- Quantifiers are greedy; add ? for lazy.
- ^ $ anchor; \b is a word boundary; re.M makes ^ $ work per line.
- Groups capture; \1 and \g<name> reuse them in sub().
- Compile patterns that are used repeatedly.
Frequently asked questions
Should I always use regex for text processing?
No. For simple tasks str methods (split, startswith, in, replace) are faster and clearer. Use regex for patterns: variable formats, validation and extraction.
Can regex validate an email address completely?
Not practically – the full standard is extremely complex. Use a simple pattern for typos and confirm the address by sending an email.
Does re.compile make code faster?
Slightly, when a pattern is used many times; Python also caches recently used patterns. The main benefit is readability and reuse.
Where can I learn more?
Read Python String Methods and The Python Standard Library in the Python tutorial, then practise with the exercises below.