Learn regular expressions
From the first character to backtracking and Unicode, one idea a lesson. Every example opens in Dotstar’s web version, so you can change it and see what happens; and where the engines disagree, each lesson says how. For which engine has which syntax at a glance, see the syntax table.
- What a regular expression is
A pattern that describes text: letters that match themselves, the first match and every match, and case.
- Special characters and escaping
The characters that mean something in a pattern, and the backslash that makes them plain again.
- Repetition
How many times: ?, *, + and {n,m}, what they repeat, and why they take as much as they can.
- Character classes
One character out of a set: brackets, ranges, negation, and the shorthands \d, \w and \s, which differ substantially between engines.
- The dot and line breaks
The dot matches any character except a line break, which characters count as line breaks depends on the engine, and the s flag includes them.
- Anchors and word boundaries
^, $, \A, \z and \b: patterns that match a position, not a character, and how to check that a whole string has the right shape.
- Groups and alternation
Either this or that with |, parentheses to group and repeat, and which alternative wins when more than one fits.
- Captures and backreferences
Parentheses that remember what they matched, numbered and named, and \1 to match the same text again.
- Replacing
Search and replace with a pattern: the groups in the replacement, the first match or every one, and a dollar sign that means a dollar.
- Greedy and lazy
Why .* takes too much, the lazy *? and +? that take as little as they can, and a negated class that is often better than either.
- Backtracking
How most engines try one way and then another, how a pattern can make that take forever, and the engines built so it can’t.
- Lookahead and lookbehind
Conditions on what comes before or after a match, without making it part of the match.
- Unicode
Letters in every script with \p{…}, what “one character” means, case beyond ASCII, and text that looks the same but isn’t.
- Common patterns, and their traps
E-mail addresses, dates, IP addresses, log lines and CSV: patterns people need every day, why each is harder than it looks, and when a regex is the wrong tool.