120 cards
A regex engine begins by deciding which characters in the input stream a token can consume. The dot metacharacter . is the most permissive token: by default it matches any single character except the newline character \n. To make it match newlines as well, you enable the dotall mode using the s flag in JavaScript and P...
Quantifiers tell the engine how many times to repeat the preceding token. The three fundamental quantifiers are * for zero or more, + for one or more, and ? for zero or one. The difference between * and + matters whenever the pattern might match an empty string: colou?r accepts both color and colour because the ? makes...
Anchors do not consume characters; they assert something about the current position in the input. The caret ^ matches the start of the string by default, and with the m flag it also matches the start of each line following a newline. The dollar sign \( matches the end of the string, and with the m flag it also matches...
Parentheses do three distinct things in regex, and a good pattern keeps them straight. A capturing group, written (...), records the text it matches so it can be referenced later. Groups are numbered left to right starting at 1, so in (\d{4})-(\d{2}) the first group captures the year and the second captures the month....
Lookarounds are zero-width assertions that test what is ahead or behind the current position without consuming characters. Positive lookahead, written (?=...), asserts that the upcoming text matches the subpattern and then returns the position to where it was, so the surrounding pattern can continue matching. The patte...
Flags change the global behavior of a regex. The case-insensitive flag i makes letter matching ignore case, so /hello/i matches Hello, HELLO, and hElLo. In Unicode-aware engines the flag also applies cross-script case folding, so it can match Straße against STRASSE. The multiline flag m changes only the behavior of the...
Real-world regex patterns solve recurring problems in input validation and text extraction. For an IPv4 address, each octet must lie in the range 0 to 255, which is most cleanly written as the alternation (25[0-5]|2[0-4]\d|[01]?\d\d?), repeated four times with literal dots between them and anchored at both ends. A prac...
Modern regex engines fall into two broad families with very different performance characteristics. A DFA, or deterministic finite automaton, runs in linear time, never backtracks, and supports every feature that can be expressed as a finite state machine. The catch is that DFAs cannot support backreferences, lookaround...