Regex

Beginner · Roadmap · 47 lessons · 9 groups

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.

0%

Not started

Nothing saved yet. Progress is kept in this browser until you sign in.

Start the path

What regex is · 4

Matching characters · 6

Repetition and choice · 5

Groups and captures · 5

Lookaround and flags · 6

Regex in code · 6

Unicode and text · 3

How engines work · 5

Recipes and practice · 7

01What 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.Beginner · 8 min02Literals and escapingMost characters in a pattern match themselves; a few do not. Learn the metacharacters, why . needs \. , and how string literals double the backslashes.Beginner · 7 min03Testing 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.Beginner · 4 min04Flavors 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.Beginner · 7 min01Character 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].Beginner · 14 min02Negated 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.Beginner · 16 min03Shorthand 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.Beginner · 9 min04The 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.Beginner · 9 min05Anchors 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.Beginner · 14 min06Word 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.Beginner · 6 min01Quantifiers: 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.Beginner · 15 min02Counted 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.Beginner · 9 min03Greedy 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.Intermediate · 13 min04AlternationThe | operator chooses between alternatives. Why it binds loosest, why JavaScript takes the first alternative that works, and how POSIX tools differ.Beginner · 5 min05How 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.Beginner · 9 min01Grouping 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.Beginner · 11 min02Capturing 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.Beginner · 14 min03Non-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.Beginner · 6 min04Named 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.Beginner · 8 min05BackreferencesA 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.Intermediate · 9 min01LookaheadCheck what comes next without consuming it: (?=...) requires, (?!...) forbids. Learn zero-width matching, the backtracking trap and which tools support it.Intermediate · 6 min02LookbehindCheck what came before the current position with (?<=...) and (?<!...). JavaScript allows any length, Python needs a fixed width, PCRE and Perl sit in between.Intermediate · 8 min03Combining lookaroundsStack lookaheads for must-contain-all rules, insert thousands separators, exclude a shape, and see when separate checks in code beat one clever pattern.Intermediate · 7 min04Flags: 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.Intermediate · 10 min05Dotall, 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.Intermediate · 15 min06Inline 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.Intermediate · 3 min01Matching 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.Intermediate · 17 min02Replacing with regexRewrite text with replace, $1, $<name> and $&, replacer functions, and Python re.sub with \1 and callables. Includes the $-in-user-text trap.Intermediate · 19 min03Splitting 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.Intermediate · 9 min04Regex 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.Intermediate · 53 min05Regex on the command linegrep, sed, pcre2grep, ripgrep and Perl speak different regex dialects. See BRE vs ERE, lazy quantifiers and lookaround compared on macOS.Intermediate · 6 min06Find 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.Intermediate · 2 min01Unicode 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.Intermediate · 16 min02Unicode 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.Intermediate · 50 min03Case 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.Intermediate · 5 min01How 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.Intermediate · 29 min02Catastrophic 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.Intermediate · 11 min03Atomic 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.Advanced · 9 min04Regular 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.Advanced · 25 min05Writing 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.Intermediate · 25 min01Validating 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.Intermediate · 8 min02Dates, 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.Intermediate · 9 min03Parsing 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.Intermediate · 14 min04Quoted 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.Intermediate · 5 min05Cleaning 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.Intermediate · 7 min06When 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.Intermediate · 10 min07Reading, 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.Intermediate · 13 min

What regex is

4 lessons

  1. 01 / 04What 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.8 min
  2. 02 / 04Literals and escapingMost characters in a pattern match themselves; a few do not. Learn the metacharacters, why . needs \. , and how string literals double the backslashes.7 min
  3. 03 / 04Testing 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.4 min
  4. 04 / 04Flavors 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.7 min

Matching characters

6 lessons

  1. 01 / 06Character 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].14 min
  2. 02 / 06Negated 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.16 min
  3. 03 / 06Shorthand 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.9 min
  4. 04 / 06The 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.9 min
  5. 05 / 06Anchors 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.14 min
  6. 06 / 06Word 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.6 min

Repetition and choice

5 lessons

  1. 01 / 05Quantifiers: 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.15 min
  2. 02 / 05Counted 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.9 min
  3. 03 / 05Greedy 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.13 min
  4. 04 / 05AlternationThe | operator chooses between alternatives. Why it binds loosest, why JavaScript takes the first alternative that works, and how POSIX tools differ.5 min
  5. 05 / 05How 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.9 min

Groups and captures

5 lessons

  1. 01 / 05Grouping 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.11 min
  2. 02 / 05Capturing 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.14 min
  3. 03 / 05Non-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.6 min
  4. 04 / 05Named 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.8 min
  5. 05 / 05BackreferencesA 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.9 min

Lookaround and flags

6 lessons

  1. 01 / 06LookaheadCheck what comes next without consuming it: (?=...) requires, (?!...) forbids. Learn zero-width matching, the backtracking trap and which tools support it.6 min
  2. 02 / 06LookbehindCheck what came before the current position with (?<=...) and (?<!...). JavaScript allows any length, Python needs a fixed width, PCRE and Perl sit in between.8 min
  3. 03 / 06Combining lookaroundsStack lookaheads for must-contain-all rules, insert thousands separators, exclude a shape, and see when separate checks in code beat one clever pattern.7 min
  4. 04 / 06Flags: 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.10 min
  5. 05 / 06Dotall, 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.15 min
  6. 06 / 06Inline 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.3 min

Regex in code

6 lessons

  1. 01 / 06Matching 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.17 min
  2. 02 / 06Replacing with regexRewrite text with replace, $1, $<name> and $&, replacer functions, and Python re.sub with \1 and callables. Includes the $-in-user-text trap.19 min
  3. 03 / 06Splitting 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.9 min
  4. 04 / 06Regex 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.53 min
  5. 05 / 06Regex on the command linegrep, sed, pcre2grep, ripgrep and Perl speak different regex dialects. See BRE vs ERE, lazy quantifiers and lookaround compared on macOS.6 min
  6. 06 / 06Find 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.2 min

Unicode and text

3 lessons

  1. 01 / 03Unicode 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.16 min
  2. 02 / 03Unicode 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.50 min
  3. 03 / 03Case 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.5 min

How engines work

5 lessons

  1. 01 / 05How 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.29 min
  2. 02 / 05Catastrophic 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.11 min
  3. 03 / 05Atomic 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.9 min
  4. 04 / 05Regular 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.25 min
  5. 05 / 05Writing 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.25 min

Recipes and practice

7 lessons

  1. 01 / 07Validating 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.8 min
  2. 02 / 07Dates, 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.9 min
  3. 03 / 07Parsing 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.14 min
  4. 04 / 07Quoted 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.5 min
  5. 05 / 07Cleaning 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.7 min
  6. 06 / 07When 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.10 min
  7. 07 / 07Reading, 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.13 min
Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark