Regex
Learn regular expressions from your first pattern to engines that run fast: character classes, quantifiers, groups, lookaround, flags, Unicode, backtracking and ReDoS, and recipes you can reuse. 47 lessons, every example run in JavaScript on Node 26, with Python, PCRE and POSIX differences shown.
What a regular expression isA regular expression describes the shape of text, not its spelling. Where regex shows up, how an engine reads a pattern, and a short history to grep.Literals and escapingMost characters in a pattern match themselves; a few do not. Learn the metacharacters, why . needs \. , and how string literals double the backslashes.Testing patterns in regex101 and the consoleThe working loop for every pattern: write it in a tester, run it on input that should match and input that should not, and check it in the flavour you ship.Flavors and the common coreRegex is one idea with many dialects. See which features every engine shares, where JavaScript, Python, PCRE, Java, Go and grep diverge, and how to probe yours.Character classesSquare brackets match one character from a set. Learn ranges, the few characters that change meaning inside brackets, and the ordering traps in [A-z] and [z-a].Negated classes[^...] matches any one character except those listed. Why [^"]* is the workhorse for quoted text, why it crosses newlines, and why it needs a character.Shorthand classes\d, \w and \s are named character classes, and \D, \W and \S are their opposites. See exactly what each matches and where flavours and locales disagree.The dot and newlinesThe dot matches almost any character, but not a line break. Which characters it skips in JavaScript, Python and Perl, and the dotall flag and [\s\S] fix.Anchors and line boundaries^ and $ match positions, not characters. Start and end of string versus line, the m flag, JavaScript's missing \A and \z, and Python's trailing-newline trap.Word boundaries\b matches the position between a word character and a non-word character. Match whole words, see why café and C++ break it, and what grep and sed accept.Quantifiers: star, plus and question*, + and ? say how many times the thing before them may repeat: zero or more, one or more, zero or one. See the zero-width match trap and the grep differences.Counted repetition{n}, {n,} and {n,m} set an exact count or a range. Build ZIP codes and hex colours with them, and see why {,3} and a stray { behave differently across flavours.Greedy and lazy quantifiersQuantifiers grab as much as they can, then give back. Compare ".*", ".*?" and "[^"]*" on one line, and see where lazy matching still goes wrong.AlternationThe | operator chooses between alternatives. Why it binds loosest, why JavaScript takes the first alternative that works, and how POSIX tools differ.How a pattern is read: precedence and groupingA regex has an order of operations: escapes, groups, quantifiers, concatenation, then alternation. Learn it, then build a pattern in tested steps.Grouping with parenthesesParentheses turn several characters into one unit, so a quantifier or a | can apply to the whole group. See ab+ vs (ab)+ and ^cat|dog$ vs ^(cat|dog)$ run.Capturing groups and numberingA capturing group saves the text its parentheses matched. Learn the numbering rule, group 0, reading groups in JavaScript and Python, and unmatched vs empty.Non-capturing groupsUse (?:...) to group without capturing. See how it keeps numbering stable and stops split and Python findall from returning pieces you did not ask for.Named capture groupsLabel a group with (?<name>...) or Python's (?P<name>...) and read it by name. Covers groups objects, $<name>, \k<name> and duplicate names.BackreferencesA backreference such as \1 or \k<name> repeats text a group already matched. Find doubled words and matching quotes, and see why it outgrows regular languages.LookaheadCheck what comes next without consuming it: (?=...) requires, (?!...) forbids. Learn zero-width matching, the backtracking trap and which tools support it.LookbehindCheck what came before the current position with (?<=...) and (?<!...). JavaScript allows any length, Python needs a fixed width, PCRE and Perl sit in between.Combining lookaroundsStack lookaheads for must-contain-all rules, insert thousands separators, exclude a shape, and see when separate checks in code beat one clever pattern.Flags: ignore case, global and multilineWhat the i, g and m flags change, why a global regex remembers lastIndex between calls, and how Python spells the same ideas with re.I and re.M instead of g.Dotall, sticky and Unicode flagsThe s flag lets . match newlines, y pins matches to lastIndex, u and v switch to code points, d reports positions. Includes Python's re.S and re.A.Inline flags and verbose modeSwitch flags inside a pattern with (?i) or (?i:...), and write long patterns with spaces and comments in verbose mode. JavaScript has no x flag.Matching in JavaScriptChoose between test, exec, match, matchAll and search by what each returns, see the g plus lastIndex bug in a validator, and avoid the string-as-pattern traps.Replacing with regexRewrite text with replace, $1, $<name> and $&, replacer functions, and Python re.sub with \1 and callables. Includes the $-in-user-text trap.Splitting and extractingSplit text on a pattern, see capture groups leak into the result, split at zero-width positions, and tokenize with match, matchAll and findall.Regex in PythonUse re.search, match and fullmatch correctly, write raw-string patterns, compile and reuse them, and read match objects. Run on Python 3.9.Regex on the command linegrep, sed, pcre2grep, ripgrep and Perl speak different regex dialects. See BRE vs ERE, lazy quantifiers and lookaround compared on macOS.Find and replace in editors, and patterns from user inputReuse capture groups in an editor's replace box, then build a regex from user text safely with RegExp.escape, and see why raw input is injection.Unicode code points and the u flagWhy /^.$/ rejects a single emoji in JavaScript, how UTF-16 code units differ from code points, and what the u flag and \u{...} change.Unicode property escapesMatch by what a character is, not which one it is, with \p{L}, \p{Script=Greek} and \p{Emoji}, and combine sets with the v flag. Where \w falls short.Case folding, normalization and graphemesWhy ignore-case misses ß and İ, why é can be two code points that a regex treats as different text, and what Intl.Segmenter counts as a character.How a backtracking engine matchesWatch a real regex engine try start positions, take as much as it can, back off one step at a time, and pick the first alternative that works.Catastrophic backtracking and ReDoSMeasure (a+)+$ doubling with every extra character, see the same cost behind two real outages, learn to spot the shape, and see which engines are immune.Atomic groups and possessive quantifiersStop the engine giving characters back. (?>...) and a++ work in PCRE, Perl, Java and Ruby. JavaScript has neither, but a lookahead can fake one.Regular languages and linear-time enginesWhy some engines cannot blow up. Simulate every possible match at once, what you give up (backreferences, lookaround), and what no regex can match.Writing patterns that run fastAnchor it, start with a literal, drop the leading .*, avoid nested quantifiers, and measure. Real timings, including three tricks that made no difference.Validating input: emails, URLs and addressesWhat a regex can check about an email, URL or IPv4 address (shape), what it cannot (that it exists), and when the platform's own parser beats a pattern.Dates, times and numbersMatch ISO dates, 24-hour times, integers, decimals and scientific notation. Learn why a regex cannot know February 30th, and where locale formats break it.Parsing log lines with named groupsBuild one real pattern from a sample access-log line, field by field, with named groups, per-field tests, and a plan for the lines that do not fit.Quoted strings and CSV fieldsMatch strings with escaped quotes, see why a near-identical pattern explodes, and know where to stop and use a real CSV parser.Cleaning and reshaping textTrim, collapse whitespace, switch camelCase and snake_case, make slugs and strip control characters with one replace each, and know when a string method wins.When not to use a regexHTML, JSON and nested expressions defeat regex for different reasons. See concrete failures, then the alternative, a regex tokenizer plus a small parser.Reading, testing and maintaining a regexRead an unfamiliar pattern in pieces, comment it where JavaScript has no verbose mode, and pin its behaviour with a should-match table run as a test.
What regex is
- What a regular expression isA regular expression describes the shape of text, not its spelling. Where regex shows up, how an engine reads a pattern, and a short history to grep.
- Literals and escapingMost characters in a pattern match themselves; a few do not. Learn the metacharacters, why . needs \. , and how string literals double the backslashes.
- Testing patterns in regex101 and the consoleThe working loop for every pattern: write it in a tester, run it on input that should match and input that should not, and check it in the flavour you ship.
- Flavors and the common coreRegex is one idea with many dialects. See which features every engine shares, where JavaScript, Python, PCRE, Java, Go and grep diverge, and how to probe yours.
Matching characters
- Character classesSquare brackets match one character from a set. Learn ranges, the few characters that change meaning inside brackets, and the ordering traps in [A-z] and [z-a].
- Negated classes[^...] matches any one character except those listed. Why [^"]* is the workhorse for quoted text, why it crosses newlines, and why it needs a character.
- Shorthand classes\d, \w and \s are named character classes, and \D, \W and \S are their opposites. See exactly what each matches and where flavours and locales disagree.
- The dot and newlinesThe dot matches almost any character, but not a line break. Which characters it skips in JavaScript, Python and Perl, and the dotall flag and [\s\S] fix.
- Anchors and line boundaries^ and $ match positions, not characters. Start and end of string versus line, the m flag, JavaScript's missing \A and \z, and Python's trailing-newline trap.
- Word boundaries\b matches the position between a word character and a non-word character. Match whole words, see why café and C++ break it, and what grep and sed accept.
Repetition and choice
- Quantifiers: star, plus and question*, + and ? say how many times the thing before them may repeat: zero or more, one or more, zero or one. See the zero-width match trap and the grep differences.
- Counted repetition{n}, {n,} and {n,m} set an exact count or a range. Build ZIP codes and hex colours with them, and see why {,3} and a stray { behave differently across flavours.
- Greedy and lazy quantifiersQuantifiers grab as much as they can, then give back. Compare ".*", ".*?" and "[^"]*" on one line, and see where lazy matching still goes wrong.
- AlternationThe | operator chooses between alternatives. Why it binds loosest, why JavaScript takes the first alternative that works, and how POSIX tools differ.
- How a pattern is read: precedence and groupingA regex has an order of operations: escapes, groups, quantifiers, concatenation, then alternation. Learn it, then build a pattern in tested steps.
Groups and captures
- Grouping with parenthesesParentheses turn several characters into one unit, so a quantifier or a | can apply to the whole group. See ab+ vs (ab)+ and ^cat|dog$ vs ^(cat|dog)$ run.
- Capturing groups and numberingA capturing group saves the text its parentheses matched. Learn the numbering rule, group 0, reading groups in JavaScript and Python, and unmatched vs empty.
- Non-capturing groupsUse (?:...) to group without capturing. See how it keeps numbering stable and stops split and Python findall from returning pieces you did not ask for.
- Named capture groupsLabel a group with (?<name>...) or Python's (?P<name>...) and read it by name. Covers groups objects, $<name>, \k<name> and duplicate names.
- BackreferencesA backreference such as \1 or \k<name> repeats text a group already matched. Find doubled words and matching quotes, and see why it outgrows regular languages.
Lookaround and flags
- LookaheadCheck what comes next without consuming it: (?=...) requires, (?!...) forbids. Learn zero-width matching, the backtracking trap and which tools support it.
- LookbehindCheck what came before the current position with (?<=...) and (?<!...). JavaScript allows any length, Python needs a fixed width, PCRE and Perl sit in between.
- Combining lookaroundsStack lookaheads for must-contain-all rules, insert thousands separators, exclude a shape, and see when separate checks in code beat one clever pattern.
- Flags: ignore case, global and multilineWhat the i, g and m flags change, why a global regex remembers lastIndex between calls, and how Python spells the same ideas with re.I and re.M instead of g.
- Dotall, sticky and Unicode flagsThe s flag lets . match newlines, y pins matches to lastIndex, u and v switch to code points, d reports positions. Includes Python's re.S and re.A.
- Inline flags and verbose modeSwitch flags inside a pattern with (?i) or (?i:...), and write long patterns with spaces and comments in verbose mode. JavaScript has no x flag.
Regex in code
- Matching in JavaScriptChoose between test, exec, match, matchAll and search by what each returns, see the g plus lastIndex bug in a validator, and avoid the string-as-pattern traps.
- Replacing with regexRewrite text with replace, $1, $<name> and $&, replacer functions, and Python re.sub with \1 and callables. Includes the $-in-user-text trap.
- Splitting and extractingSplit text on a pattern, see capture groups leak into the result, split at zero-width positions, and tokenize with match, matchAll and findall.
- Regex in PythonUse re.search, match and fullmatch correctly, write raw-string patterns, compile and reuse them, and read match objects. Run on Python 3.9.
- Regex on the command linegrep, sed, pcre2grep, ripgrep and Perl speak different regex dialects. See BRE vs ERE, lazy quantifiers and lookaround compared on macOS.
- Find and replace in editors, and patterns from user inputReuse capture groups in an editor's replace box, then build a regex from user text safely with RegExp.escape, and see why raw input is injection.
Unicode and text
- Unicode code points and the u flagWhy /^.$/ rejects a single emoji in JavaScript, how UTF-16 code units differ from code points, and what the u flag and \u{...} change.
- Unicode property escapesMatch by what a character is, not which one it is, with \p{L}, \p{Script=Greek} and \p{Emoji}, and combine sets with the v flag. Where \w falls short.
- Case folding, normalization and graphemesWhy ignore-case misses ß and İ, why é can be two code points that a regex treats as different text, and what Intl.Segmenter counts as a character.
How engines work
- How a backtracking engine matchesWatch a real regex engine try start positions, take as much as it can, back off one step at a time, and pick the first alternative that works.
- Catastrophic backtracking and ReDoSMeasure (a+)+$ doubling with every extra character, see the same cost behind two real outages, learn to spot the shape, and see which engines are immune.
- Atomic groups and possessive quantifiersStop the engine giving characters back. (?>...) and a++ work in PCRE, Perl, Java and Ruby. JavaScript has neither, but a lookahead can fake one.
- Regular languages and linear-time enginesWhy some engines cannot blow up. Simulate every possible match at once, what you give up (backreferences, lookaround), and what no regex can match.
- Writing patterns that run fastAnchor it, start with a literal, drop the leading .*, avoid nested quantifiers, and measure. Real timings, including three tricks that made no difference.
Recipes and practice
- Validating input: emails, URLs and addressesWhat a regex can check about an email, URL or IPv4 address (shape), what it cannot (that it exists), and when the platform's own parser beats a pattern.
- Dates, times and numbersMatch ISO dates, 24-hour times, integers, decimals and scientific notation. Learn why a regex cannot know February 30th, and where locale formats break it.
- Parsing log lines with named groupsBuild one real pattern from a sample access-log line, field by field, with named groups, per-field tests, and a plan for the lines that do not fit.
- Quoted strings and CSV fieldsMatch strings with escaped quotes, see why a near-identical pattern explodes, and know where to stop and use a real CSV parser.
- Cleaning and reshaping textTrim, collapse whitespace, switch camelCase and snake_case, make slugs and strip control characters with one replace each, and know when a string method wins.
- When not to use a regexHTML, JSON and nested expressions defeat regex for different reasons. See concrete failures, then the alternative, a regex tokenizer plus a small parser.
- Reading, testing and maintaining a regexRead an unfamiliar pattern in pieces, comment it where JavaScript has no verbose mode, and pin its behaviour with a should-match table run as a test.