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.

  1. What a regular expression is

    A pattern that describes text: letters that match themselves, the first match and every match, and case.

  2. Special characters and escaping

    The characters that mean something in a pattern, and the backslash that makes them plain again.

  3. Repetition

    How many times: ?, *, + and {n,m}, what they repeat, and why they take as much as they can.

  4. Character classes

    One character out of a set: brackets, ranges, negation, and the shorthands \d, \w and \s, which differ substantially between engines.

  5. 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.

  6. 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.

  7. Groups and alternation

    Either this or that with |, parentheses to group and repeat, and which alternative wins when more than one fits.

  8. Captures and backreferences

    Parentheses that remember what they matched, numbered and named, and \1 to match the same text again.

  9. 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.

  10. 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.

  11. 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.

  12. Lookahead and lookbehind

    Conditions on what comes before or after a match, without making it part of the match.

  13. Unicode

    Letters in every script with \p{…}, what “one character” means, case beyond ASCII, and text that looks the same but isn’t.

  14. 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.