Lesson · Regular Expressions
Regex Fundamentals
55 min readRegex Fundamentals
Regular expressions describe text patterns with a compact language. They are excellent for local pattern recognition and a poor substitute for a real parser when the grammar becomes nested or complex.
Learning goals
- Read a pattern left to right and name the job of each part: anchors, character classes, quantifiers, groups, alternation.
- Predict which text a greedy quantifier captures versus a lazy one on the same input.
- Use
fullmatch,search, andfindallfor the right question and predict the shape of each return value. - Escape metacharacters so literal dots and brackets match literally, and explain why raw strings help.
- Decide when a text task needs a parser instead of a bigger pattern.
Mental model
Read the pattern left to right: an anchor pins the engine to a position, a character class consumes exactly one character from a set, and a quantifier repeats the element before it. Groups and alternation combine those units into branches, and escaping removes the special meaning when you need a literal character. Matching succeeds when the engine consumes the text while every anchor holds, which is why fullmatch suits whole-string validation.
Mental model
read it top to bottom
^ [A-Za-z] [A-Za-z0-9_]{2,15} $
anchor class quantifier anchor
pin start one letter repeat 2 to 15 times pin endCore idea
A regex is a small program that consumes text one character at a time: classes say which characters are allowed, quantifiers say how many can appear, and anchors say where the engine may start and stop. Groups and alternation are the composition layer on top, letting one pattern express choices and capture the pieces that matter. The practical rule is to match the smallest text region that answers your actual question, and to hand anything nested or recursive to a parser.
Patterns
A pattern is the text description of what to match, written in the regex language and compiled by re.compile() into a re.Pattern object. Compiling checks the syntax once, so one object can drive many matches and a malformed pattern raises re.error immediately rather than mid-search.
Character classes
A character class matches one character from a set or category. Be explicit about Unicode versus ASCII expectations when character semantics matter.
Quantifiers
Quantifiers specify how many repetitions of a preceding pattern are accepted. Greedy and lazy behavior can change which text a larger pattern captures.
Groups
Regex groups control precedence and can capture submatches. Named groups make extraction code more maintainable than relying on positional group numbers.
Alternation
Alternation is the | operator: it matches the branch on its left or the branch on its right, trying each in order. It binds more loosely than concatenation, so (cat|dog)s groups the choice before the suffix while cat|dogs matches either full word.
Anchors
Anchors match positions such as the start or end of text rather than consuming characters. Choose fullmatch() when the entire input must conform to a pattern.
Escaping
Escaping puts a backslash before a character that would otherwise be special, so \. matches a literal dot and \[ a literal bracket. Write patterns as raw strings such as r"\d\.\d" so Python does not process the backslashes first, and call re.escape() to quote literal text that may contain metacharacters.
Walkthrough
re.compile(r"^[A-Za-z][A-Za-z0-9_]{2,15}$")parses the pattern once into aPatternobject; the raw string keeps every backslash intact for the regex engine.^and$pin the match to the whole string,[A-Za-z]requires a leading letter, and{2,15}lets the class[A-Za-z0-9_]repeat until the identifier is 3 to 16 characters long.pattern.fullmatch(candidate)returns aMatchobject when the entire candidate conforms andNoneotherwise;bool()reduces that to theTrueorFalseprinted beside each candidate.- Predict before running: which candidates print
True, why"ok"fails even though both characters are legal, and what verdict"A_9"gets.
Experiments to try
- Loosen
{2,15}to{1,15}and rerun the loop; then tighten the leading class to[A-Z]and record which candidates change verdict. - Compare
re.search(r"\d+", "order 42")withre.match(r"\d+", "order 42")and explain why one finds the number and the other returnsNone. - Compile
r"(?P<word>[a-z]+)(?P<num>\d+)$"and printgroupdict()for"item42"; repeat with an unnamed group and comparegroup(1)access. - Run
re.search(r"<.+>", "<a><b>")andre.search(r"<.+?>", "<a><b>")side by side and account for the different spans.
Common mistakes
- Assuming
re.matchscans the text: it anchors at position 0 only, sore.match(r"\d", "x1")returnsNonewhilere.search(r"\d", "x1")finds the digit. - Forgetting that
$also matches just before a trailing newline:re.match(r"\w+$", "abc\n")succeeds, so validate whole strings withfullmatchwhen a stray newline must fail. - Treating
\d,\w, and\sas ASCII: they match Unicode digits and letters by default, so use[0-9]orre.ASCIIwhen only ASCII is acceptable. - Interpolating raw input into a pattern: a dot or bracket from the input changes the pattern's meaning, so quote literals with
re.escape.
Practice: Easy
- Predict the verdict for four candidates through the worked pattern:
"ada_1","1bad","ok","A_9". Run the loop and name the rule each failing candidate breaks. - Change
{2,15}to{1,15}, then to{3,15}, and report the shortest and longest identifiers each version accepts. - Write a pattern for a six-digit hex color such as
"#1a2b3c"using one literal, one character class, and one quantifier; test it withfullmatchon valid and invalid samples.
Practice: Medium
- Write an unbounded identifier pattern
r"[A-Za-z_][A-Za-z0-9_]*"and compare it with the worked example's bounded version; list the inputs each accepts that the other rejects. - Extend the worked pattern with alternation so plain lowercase words such as
"ok"pass as well, test both branches, and explain why the|needs grouping when you add more context around it. - Capture with named groups: compile
r"(?P<user>[a-z_]+)-(?P<id>\d+)$", printgroupdict()for"ada-42", and predict the result for"ada-42x"and"42-ada"before running.
Practice: Hard
- Build a
validate_identifier(candidate)function for the worked rule: returnNonefor valid input and a short message naming the first violated rule. Cover empty input, a leading digit, a leading underscore, the length bounds 3 and 16, and an illegal character, with tests written first. - Escaping lab: show how
r"3.14"also matches"3-14"and howr"file.txt$"matches"fileXtxt"; repair both with escaped dots and confirmre.escapereproduces the repair when the literal comes from a variable. - Explain why no regex can validate balanced parentheses such as
"((1+2)*(3+4))", and describe what kind of tool handles that grammar instead.
Lesson checklist
- I can read
^[A-Za-z][A-Za-z0-9_]{2,15}$part by part and say what each piece enforces. - I can choose between
fullmatch,search, andfindallfor a given question and predict the return shape. - I can predict greedy versus lazy behavior for
.*on a concrete input. - I can escape a literal dot or bracket correctly and explain why raw strings matter.
Remember
A pattern is built from a small vocabulary: anchors pin positions, classes consume single characters, quantifiers set repetition, and groups or alternation compose the pieces. The worked example shows the full loop, compile once and judge each candidate with `fullmatch`, which succeeds only when the whole input conforms. Remember the defaults that bite quietly: shorthand classes are Unicode-aware, `$` tolerates a trailing newline, and `re.match` never searches past position 0.
Interview angles
What is the main purpose of **Patterns**?+
A pattern is the description of the text you want to match, written in the regex language. re.compile() turns it into a reusable Pattern object, checking the syntax once and raising re.error when the pattern is malformed.
What should you pay attention to when using **Character classes**?+
A character class matches one character from a set or category. Be explicit about Unicode versus ASCII expectations when character semantics matter.
How does **Quantifiers** fit into this lesson?+
Quantifiers specify how many repetitions of a preceding pattern are accepted. Greedy and lazy behavior can change which text a larger pattern captures.
Does `re.match(r"\d+", "item 42")` find the number, and why?+
No. re.match anchors the attempt at position 0 and the text starts with i, so it returns None; re.search scans forward and finds 42.