Pattern Basics
~320 words ยท 2 min read
Regex Pattern Basics
A regular expression is a compact pattern that describes text. Most engines share the same core syntax: literals, wildcards, character classes, quantifiers, and anchors.
Literals and the Dot
Most characters match themselves literally. The dot . is the wildcard โ it matches any single character except a newline by default.
/c.t/ matches "cat", "cot", "c9t" โ not "ct"
Character Classes
Square brackets define a set of allowed characters. A range uses a hyphen, and a leading ^ inside the brackets negates the set.
/[aeiou]/ any vowel
/[a-z]/ any lowercase letter
/[^0-9]/ anything that is NOT a digit
Common classes have shorthand forms: \d (digit), \w (word character), \s (whitespace). Their uppercase versions negate them.
Quantifiers
Quantifiers control how many times the preceding element repeats.
*โ zero or more+โ one or more?โ zero or one (optional){n,m}โ between n and m times
/colou?r/ "color" or "colour"
/\d{3}-\d{4}/ "555-1234"
/a+/ "a", "aa", "aaa", ...
Greedy vs Lazy
By default quantifiers are greedy: they match as much as possible. Adding ? after a quantifier makes it lazy, matching as little as possible.
/<.*>/ greedy on "<a><b>" matches the WHOLE string
/<.*?>/ lazy matches just "<a>"
Greedy matching is a frequent source of surprises. When parsing tags or delimited fields, reach for the lazy
*?or+?โ it usually gives the match you actually wanted.
Anchors
Anchors do not consume characters โ they assert a position. ^ matches the start of the string; $ matches the end.
/^\d+$/ the entire string must be digits
/^Hello/ the string must start with "Hello"