Regex Cheatsheet

Regular expression syntax and how engines really differ: character classes, quantifiers, anchors, groups and lookaround, then Go RE2 against Python, JavaScript and PCRE, what Go refuses to compile and how to rewrite it, the regexp API and named captures, patterns with their pitfalls, and playbooks for catastrophic backtracking and patterns that do not match. Each entry gives the problem, how it works, examples run on real engines, real-world notes and trade-offs.

Updated: 2026-10-11

29 entries

Quick tables

Reference and comparison tables for quick scanning.

Syntax quick reference

One line per token, with a minimal example and what differs between Go (RE2), Python 3.13 `re`, JavaScript (Node 22) and PCRE2. Every row was run: Go 1.24, Python 3.13.16, Node 22.22.0, and libpcre2-8 10.42, the library behind GNU `grep -P` (cross-checked against `grep -P` on about 580 single-line cases). As of 2026-10.

Syntax quick reference
TokenMeaningMinimal exampleEngine differences
`.`Any character except a line terminator`a.c` on `abc` → `abc`; on `a\nc` → no matchJavaScript also excludes `\r`, U+2028 and U+2029. `s` / `(?s)` includes newlines everywhere.
`\d` `\D`Digit / non-digit`\d+` on `x42` → `42`ASCII in Go, JavaScript and PCRE2; Python also matches `٣` (U+0663) unless `re.ASCII`.
`\w` `\W`Word character `[A-Za-z0-9_]` / its negation`\w+` on `café` → `caf` (Python: `café`)Python is Unicode-aware by default; the other three are ASCII-only.
`\s` `\S`Whitespace / non-whitespace`\s` on `a b` → the spaceGo: `[\t\n\f\r ]` only. PCRE2 adds vertical tab. Python and JavaScript also match U+00A0 and U+2003.
`[abc]` `[^abc]` `[a-z]`Set, negated set, range`[^0-9]+` on `ab1` → `ab``[]a]` is a set with `]` in Go, Python, PCRE2; in JavaScript `[]` is empty and `[^]` is any character. `[\w-.]` fails in Python, PCRE2 and JavaScript with `u`.
`[[:alpha:]]`POSIX class`[[:alpha:]]+` on `ab1` → `ab`Go and PCRE2 only; Python and JavaScript find nothing.
`*` `+` `?`Zero or more, one or more, zero or one (greedy)`ab*` on `abbb` → `abbb`Same in all four.
`{n}` `{n,}` `{n,m}`Counted repetition`a{2,4}` on `aaaaa` → `aaaa`Go caps counts at 1000 (`invalid repeat count`), PCRE2 at 65535. `{,n}` means `{0,n}` in Python only (PCRE2 10.43+ also; 10.42 is literal). An invalid brace is literal text.
`*?` `+?` `??` `{n,m}?`Lazy (fewest first)`<.+?>` on `<a><b>` → `<a>`Same in all four.
`*+` `++` `?+` `{n,m}+`Possessive (no give-back)`a*+a` on `aaa` → no matchPython 3.11+ and PCRE2 only. Go: `invalid nested repetition operator`; JavaScript: `Nothing to repeat`.
`^` `$`Start / end of input (of each line with `m`)`^\d+$` on `12\n` → Go no, JavaScript no, Python `12`, PCRE2 `12`Python and PCRE2 `$` also match before a final `\n` (`grep -P` does not). JavaScript `m` also splits on `\r`.
`\A` `\z` `\Z`Absolute start / absolute end / end or before final newline`\A\d+\z` on `12\n` → no match`\A`: not JavaScript. `\z`: Go, PCRE2. `\Z`: Python, PCRE2.
`\b` `\B`Word boundary / not a boundary`caf\b` on `café` → `caf` in Go, JavaScript, PCRE2; no match in PythonPython's `\b` is Unicode-aware; the others use ASCII `\w`.
`(...)`Capturing group`(\d+)-(\d+)` on `1-2` → groups `1`, `2`Numbered by opening parenthesis in all four.
`(?:...)`Non-capturing group`(?:ab)+` on `abab` → `abab`Same in all four.
`(?P<n>...)` `(?<n>...)` `(?'n'...)`Named group`(?<y>\d{4})` on `2026` → `y` = `2026``?P<`: Go, Python, PCRE2. `?<`: Go, JavaScript, PCRE2. `?'`: PCRE2 only.
`a|b`Alternation, lowest precedence, leftmost-first`a|ab` on `ab` → `a`POSIX ERE (`grep -E`) picks the longest: `ab`.
`\1`Backreference`(a)\1` on `aa` → `aa`Go: compile error `invalid escape sequence: `\1``. PCRE2 also has `\g1` and `\k<n>`.
`(?=...)` `(?!...)` `(?<=...)` `(?<!...)`Lookahead / lookbehind`foo(?=bar)` on `foobar` → `foo`Go: none. Python: fixed-width lookbehind. JavaScript: any width. PCRE2: fixed per branch.
`(?>...)`Atomic group`(?>a+)a` on `aaa` → no matchPython 3.11+ and PCRE2 only.
`(?i)` `(?i:...)`Inline flags (whole rest of group / one group)`(?i)abc` on `ABC` → `ABC`Go, Python (global form only at the start), PCRE2. None in JavaScript on Node 22.
`\p{L}`Unicode property`\p{L}+` on `café` → `café`Go, PCRE2 (in UTF mode); JavaScript with `u` or `v`; none in Python `re`.
`\Q...\E`Literal text span`\Qa.b\E` on `a.b` → `a.b`Go and PCRE2. Python: `bad escape \Q`. JavaScript reads `\Q` as the letter `Q`.
`\x41` `\x{41}`Code point by hex`\x41` on `A` → `A``\x{...}`: Go, PCRE2. `\u{...}`: JavaScript with `u`. Four-digit `\u` escapes: Python, JavaScript.

The PCRE2 results use default library options. `grep -P` differs in two respects: it sets DOLLAR_ENDONLY and does not enable multiline. POSIX ERE (`grep -E`, `sed -E`) is not tabulated here: it has no `\d`, `(?:...)` or lookaround, and picks the longest alternative.

Flags across engines

What each engine calls a flag, whether it can appear inside the pattern, and what happens when it is wrong. Observed on Go 1.24, Python 3.13.16, Node 22.22.0 (V8 12.4) and libpcre2-8 10.42. Older Python versions and newer V8 versions may differ (as of 2026-10).

Flags across engines
NeedGoPython 3.13JavaScript (Node 22)PCRE2 10.42
Ignore case`(?i)``re.I`, `(?i)``/i``(?i)`
Multiline `^` `$``(?m)``re.M`, `(?m)``/m` (also splits on `\r`, U+2028, U+2029)`(?m)`
Dot matches newline`(?s)``re.S`, `(?s)``/s``(?s)`
Comments and whitespace (verbose)None: `(?x` gives `invalid or unsupported Perl syntax: `(?x```re.X`, `(?x)`, `(?x:...)`None (build the pattern from commented strings)`(?x)`; `(?xx)` also ignores spaces inside `[...]`
Ungreedy (swap greedy and lazy)`(?U)`NoneNone`(?U)`
Unicode modeAlways UTF-8Default for `str` patterns`/u`, `/v``(*UTF)`, `(*UCP)`; `grep -P` enables UTF in UTF-8 locales
ASCII-only `\w \d \s \b`Default`re.A`, `(?a)`Default (the `u` flag does not change it)Default (without `(*UCP)`)
All matches (global)`FindAll*`, `ReplaceAll*``findall`, `finditer`, `sub` (`count=` limits)`/g`; `replaceAll` requires itCaller loops; substitute-global option
Sticky (match at an offset)None`pattern.match(s, pos)``/y` with `lastIndex``\G` anchor (compiles; offset behaviour per the docs)
Match indexes`FindStringSubmatchIndex``m.span()`, `m.start(n)``/d` gives `m.indices`Offsets from the match API
Set operations in classesNoneNone`/v`: `[\p{L}--[a-z]]`, `&&`None
Flag in the middle of a pattern`a(?i)b` works; applies to the rest of the group`a(?i)b` is an error: `global flags not at the start of the expression`Not available (`Invalid group`)`a(?i)b` works; applies to the rest of the group
Scoped `(?i:...)` and `(?-i:...)`YesYes; a bare `(?-i)` is `missing :`No (Node 22: `Invalid group`)Yes
Extra inline lettersOnly `i m s U``a i m s u x` (`L` is an error for `str`)None`(?J)` duplicate names, `(?n)` no auto-capture
Invalid or repeated flag`(?g` gives `invalid or unsupported Perl syntax: `(?g```(?g)` gives `unknown extension ?g`; `re.A | re.U` gives `ASCII and UNICODE flags are incompatible``gg` or `uv` gives `Invalid flags supplied to RegExp constructor 'gg'``(?g)` gives `unrecognized character after (? or (?-`

Go's `U` is "ungreedy", not Unicode. JavaScript `g` and `y` make the regex object stateful through `lastIndex`. Python's `re.UNICODE` is a no-op for `str` patterns and `re.LOCALE` is an error for them.

Escaping rules and escape functions

Which characters need a backslash outside and inside `[...]`, where the engines disagree, and what each escape function does. The probe string for the functions was `.+*?()|[]{}^$\` followed by space, `-#&~/<>=!:,@_%"'`, a tab and a newline. Observed on Go 1.24, Python 3.13.16, Node 22.22.0 and libpcre2-8 10.42 (as of 2026-10).

Escaping rules and escape functions
Character or needOutside a classInside a classDifferences between engines
`\`Write `\\`. A bare trailing `\` is a compile error in all fourWrite `\\`. A bare `\` is a compile error in all fourNo differences.
`.` `|` `^` `$`Escape to match literally; bare, they keep their operator meaningLiteral; `^` is special only in first positionNo differences.
`*` `+` `?` `(` `)` `[`Escape; bare is a compile error in all fourLiteral (including `[` and `(`)Messages differ: `missing argument to repetition operator` (Go), `nothing to repeat` (Python), `Nothing to repeat` (JavaScript), `quantifier does not follow a repeatable item` (PCRE2).
`{` `}`Escape to be safe; a brace that is not a valid quantifier is literalLiteralJavaScript with `u` or `v`: a bare `{`, `}` or `]` is a compile error (`Lone quantifier brackets`).
`]`LiteralEscape (`\]`) unless it is the first character: `[]a]` works in Go, Python, PCRE2JavaScript: `[]` is an empty class, so `[]a]` does not work; with `u` or `v` a bare `]` outside a class is an error.
`^` in a class(see `.` `|` `^` `$`)Negates when first; escape it (`\^`) or move it`[^]` is a compile error in Go, Python, PCRE2 and "any character" in JavaScript.
`-`Literal; `\-` is accepted except in JavaScript with `u` (`Invalid escape`)Range operator between two items; literal when first, last or escaped`[\w-.]` is an error in Python, PCRE2 and JavaScript with `u` or `v`, and accepted in Go and in JavaScript without `u`; write `[\w.-]`.
`/`No escape needed; `\/` is acceptedNo escape needed; `[\/]` is acceptedA JavaScript regex literal `/.../` needs `\/` outside a class; `new RegExp("a/b")` does not.
Space, `#`, `&`, `~`Plain characters; special only under `x` (Python, PCRE2)Plain (spaces inside a class stay significant under `x`; PCRE2 `xx` ignores them)`\ ` `\#` `\&` `\~` are accepted by Go, Python and PCRE2; JavaScript with `u` gives `Invalid escape`.
Letters and digits after `\`Only defined escapes: Go, Python and PCRE2 reject the rest (`\y`)SameJavaScript without `u` accepts `\y` as `y` and `\e` as `e`; with `u` it is an error.
`\Q...\E`Literal span in Go and PCRE2Not allowed in a Go class (`invalid escape sequence: `\Q``); works in PCRE2Python: `bad escape \Q`. JavaScript reads it as the letter `Q`. In PCRE2 a `\E` inside the quoted text ends the span early.
Go: `regexp.QuoteMeta(s)`Backslash-escapes only `\ . + * ? ( ) | [ ] { } ^ $`Not enough for a class: it leaves `-` and `^` mid-text aloneLeft unescaped: space, `-`, `#`, `&`, `~`, `/`, `<`, `>`, `=`, `!`, `:`, `,`, `@`, `_`, `%`, quotes, tab, newline.
Python: `re.escape(s)`Since 3.7 escapes the QuoteMeta set plus space, `-`, `#`, `&`, `~`, tab and newlineSafe inside a class: it escapes `-`, `^`, `]` and `\`Leaves `/ < > = ! : , @ _ % " '` alone.
JavaScript: no built-in`typeof RegExp.escape` is `undefined` on Node 22.22; the usual idiom is `s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")`The idiom does not escape `-`, so it is unsafe for a class built from user textOn the probe string the idiom produced exactly the same output as Go's `QuoteMeta`.
PCRE2: `\Q...\E`Wrap the text in `\Q...\E` (or use `grep -F` for fixed strings)`[\Q...\E]` works, with the same `\E` caveatPCRE2 has no quote function in the library; host languages add their own.

Rule of thumb: escape only the fourteen syntax characters `\ . + * ? ( ) | [ ] { } ^ $` and a literal `-` inside a class; avoid escaping anything else, because JavaScript with `u` rejects most identity escapes and Go, Python and PCRE2 reject unknown letters.

Replacement strings across engines

How to reference captures and write a literal `$` or backslash in a replacement. The PCRE2 column is the library's own `pcre2_substitute` syntax, observed through a small C harness against libpcre2-8 10.42; PHP, Perl and other hosts define their own templates and are not covered. GNU sed 4.x was run with `-E`; BSD sed is not covered here. Observed on Go 1.24, Python 3.13.16 and Node 22.22.0 (as of 2026-10).

Replacement strings across engines
NeedGo `ReplaceAllString`Python `re.sub`JavaScript `replace`PCRE2 `pcre2_substitute`GNU `sed -E`
Group by number`$1`, `${1}``\1`, `\g<1>``$1``$1`, `${1}``\1`
Digit right after the reference`${1}0`; `$10` is group 10 (empty)`\g<1>0`; `\10` is `invalid group reference 10``$10` with one group gives group 1 plus `0`; `${1}` is not syntax`${1}0`; `$10` is `unknown substring``\10` is group 1 plus `0`
Whole match`$0`, `${0}``\g<0>` (`\0` is a NUL character)`$&` (`$0` stays literal)`$0`, `${0}``&`, `\0`; literal ampersand `\&`
Named group`${name}`, `$name` (`$x1` means group `x1`)`\g<name>``$<name>`, only if the regex has named groups`${name}`, `$name`None
Literal `$``$$``$``$$``$$`; a lone trailing `$` is `invalid replacement string``$`
Backslash and `\n`Kept as typed (`\n` is two characters)`\\` is one backslash; `\n` is a newline; `\q` is `bad escape \q`Kept as typedKept as typed; the extended option processes `\n`, `\\`, `\x41``\\` is one backslash; `\n` is a newline
Group that does not existEmpty (`$2` with one group)Error: `invalid group reference 2`Kept literally (`$2`)Error: `unknown substring`Compile error: `invalid reference \2 on `s' command's RHS`
Group that did not take partEmptyEmptyEmptyError `requested value is not set`; empty with the unset-empty optionEmpty
Text before / after the matchNoneNone`` $` `` and `$'`NoneNone
Case conversionCallback: `ReplaceAllStringFunc` with `strings.ToUpper`Callable: `lambda m: m.group(1).upper()`Function: `m => m.toUpperCase()`Extended option: `\U$1\E` gives `AB CD``\U\1`
Replacement as plain text`ReplaceAllLiteralString`Callable returning the textFunction returning the textLiteral option (`$1$$` stays as typed)Escape `\` and `&` by hand
First or allAllAll; `count=` limitsFirst unless `g`; `replaceAll` needs `g`Global option needed for allFirst; `g` for all
Empty matches: `a*` → `-` on `baac``-b-c-``-b--c-``-b--c-``-b--c-` (global)`-b-c-`

Pasting a template between languages usually fails silently: Python with `$2 $1` outputs `$2 $1`, Go, JavaScript and PCRE2 with `\2 \1` output `\2 \1`. A callback or a literal-replace function avoids template syntax when the replacement comes from user input.

Engine feature matrix

Every cell comes from compiling and running the pattern on the engine named in the header. Error texts are verbatim, except that JavaScript messages are shown without the `Invalid regular expression: /…/: ` prefix Node adds. `yes` means it compiled and matched the sample input.

Engine feature matrix
FeatureGo RE2Python 3.13 reJavaScript (Node 22)PCRE2 (grep -P)POSIX ERE (grep -E)
Lookahead `(?=…)` `(?!…)`error: `invalid or unsupported Perl syntax: `(?=``yesyesyesno: `?` right after `(` is dropped with the warning `? at start of expression`
Lookbehind, fixed width `(?<=a)b` `(?<!a)b`error: `invalid named capture: `(?<=a)b``yesyesyesno (same warning as lookahead)
Lookbehind, alternatives of different length `(?<=a|bc)d`error (as above)error: `look-behind requires fixed-width pattern` (`(?<=ab|cd)e` is accepted)yesyesno
Lookbehind, variable width `(?<=a+)b`, `(?<=a{1,2})b`error (as above)error: `look-behind requires fixed-width pattern`yeserror: `lookbehind assertion is not fixed length`no
Atomic group `(?>a+)b`error: `invalid or unsupported Perl syntax: `(?>``yes (Python 3.11+)error: `Invalid group`yesno
Possessive quantifier `a*+a`error: `invalid nested repetition operator: `*+``yes (no match on `aaa`)error: `Nothing to repeat`yes (no match on `aaa`)accepted but not possessive: it means `(a*)+` and matches `aaa`
Numbered backreference `(a)\1`error: `invalid escape sequence: `\1``yesyesyesyes (GNU extension, not in POSIX ERE)
Named group `(?P<n>…)`yesyeserror: `Invalid group`yesno
Named group `(?<n>…)`yes (Go 1.22+)error: `unknown extension ?<n at position 1`yesyesno
Named group `(?'n'…)`error: `invalid or unsupported Perl syntax: `(?'``error: `unknown extension ?' at position 1`error: `Invalid group`yesno
Named backreferenceerror: `\k` and `(?P=n)` are both rejected (`invalid escape sequence: `\k``, `invalid or unsupported Perl syntax: `(?P``)`(?P=n)` yes; `\k<n>` error: `bad escape \k at position 8``\k<n>` yes; `(?P=n)` error: `Invalid group``(?P=n)`, `\k<n>`, `\k{n}`, `\g{n}`, `\k'n'` yesno
Duplicate group names `(?<n>a)(?<n>b)`accepted; `SubexpIndex("n")` returns the first, 1error: `redefinition of group name 'n' as group 2; was group 1 at position 12`error: `Duplicate capture group name` (also across `|` branches on Node 22)error: `two named subpatterns have the same name (PCRE2_DUPNAMES not set)`; `(?J)` allows itno
Conditional `(a)?(?(1)b|c)`error: `invalid or unsupported Perl syntax: `(?(``yeserror: `Invalid group`yesno
Recursion `(?R)` and subroutine calls `(?1)`error: `invalid or unsupported Perl syntax: `(?R``error: `unknown extension ?R at position 12`error: `Invalid group`yes: `\((?:[^()]|(?R))*\)` matched `(a(b))`no
Unicode property `\p{L}`yes; `\p{Han}` and `\pL` also workerror: `bad escape \p at position 0`only with `u` or `v`: `\p{Script=Han}` yes, `\p{Han}` error `Invalid property name`; without `u`, `\p{L}` is the literal text `p{L}`yes (UTF mode)no
Grapheme cluster `\X`error: `invalid escape sequence: `\X``error: `bad escape \X at position 0`no: literal `X`; with `u`, error `Invalid escape`yesno
Start and end of text `\A` `\z` `\Z``\A` yes, `\z` yes, `\Z` error `invalid escape sequence: `\Z```\A` yes, `\Z` yes (end only), `\z` error `bad escape \z at position 0` on 3.13none of the three: they are the literal letters `A`, `Z`, `z`all three; `\Z` also matches before a final newlineno
`$` before a trailing newline (`^\d+$` on `12\n`)no matchmatch (`12`); `\Z` and `fullmatch` do not matchno matchdefault PCRE2 and Perl: match (Perl run as an aside); `grep -Pz` observed no match, `\Z` matchedn/a, matching is per line
Inline flags `(?i)` and `(?i:…)`yes, also in the middle of a pattern; also `(?U)` to swap greediness`(?i)` only at the start (otherwise `global flags not at the start of the expression at position 1`); `(?i:…)` and `(?-i:…)` yesnone on Node 22 (`Invalid group`); use the `i` flagyes, anywhereno; use `grep -i`
Dot matches newline: `(?s)`yesyes`s` flag onlyyes (needs `-z` for a newline inside a record)no
Verbose mode `(?x)`error: `invalid or unsupported Perl syntax: `(?x``yes (`re.X`, or `(?x)` at the start)noyesno
Comment group `(?#…)`error: `invalid or unsupported Perl syntax: `(?#``yeserror: `Invalid group`yesno
Lazy quantifier `a+?`yesyesyesyesparsed as `(a+)?` and is greedy: matched `aaa`
Which alternative wins (`a|ab` on `ab`)leftmost-first: `a` (`Longest()` switches to `ab`)leftmost-first: `a`leftmost-first: `a`leftmost-first: `a`leftmost-longest: `ab`
Literal span `\Q…\E`yeserror: `bad escape \Q at position 0`no: matches the letters `Q`, `E`yesno
Keep-out `\K` and branch reset `(?|…)`error: `invalid escape sequence: `\K``; `(?|` is `invalid or unsupported Perl syntax`error: `bad escape \K at position 0`; `unknown extension ?| at position 1``\K` is the letter `K`; `(?|` is `Invalid group`yes, bothno
POSIX bracket class `[[:alpha:]]`yesno: parsed as a set of the characters `[:alph` followed by `]`no: same reading as Pythonyesyes
`\d` `\w` `\s` scopeASCII onlyUnicode for `str` patterns (`\d` matched `٣`, `\w` matched `é`); `re.A` restrictsASCII only, even with `u`ASCII only unless `(*UCP)`; `(*UCP)\w` matched `é`, `(*UCP)\d` matched `٣``\d` not supported (matches the letter `d`); `\w` `\s` `\b` `\<` `\>` are GNU extensions, `\w` is locale-aware
Code point escape`\x{41}` yes; `\u` error`\u0041` yes; `\x{41}` error `incomplete escape \x at position 0``\u0041` yes; `\u{41}` only with `u`; `\x{41}` means `x` repeated 41 times`\x{41}` yes; `\u` error `PCRE2 does not support \F, \L, \l, \N{name}, \U, or \u`no
Repeat count limit1000, also for nested products: `a{1001}` and `(a{500}){500}` give `invalid repeat count``a{100000}` compiles; `a{4294967295}` gives `the repetition number is too large``a{99999999999999}` compiles; no cap observed65535; `a{65536}` gives `number too big in {} quantifier`32767; `a{32768}` gives `Regular expression too big`
`{,n}` (no minimum)literal textmeans `{0,n}`literal textliteral text on PCRE2 10.42; PCRE2 10.43 and later (like Perl 5.34+) read it as `{0,n}`, per the PCRE2 ChangeLogmeans `{0,n}`
Worst case on `^(a+)+$` against `aaa…b`linear (each doubling of input about doubled the time)exponential (about 4x per two extra characters)exponential (about 4x per two extra characters)exponential until the backtracking limit: `exceeded PCRE's backtracking limit` from 23 characters (22 answered)linear (flat up to 160000 characters)

As of 2026-10: Go 1.24.7 `regexp`, Python 3.13.16 `re`, Node v22.22.0 (V8 12.4), GNU grep 3.11 linked to PCRE2 10.42 (`grep -P`), GNU grep 3.11 `-E`, run in the `C.utf8` locale. Probes used the pattern text as written, searched ASCII or short Unicode samples, and read the first match. Timing rows give growth trend only. Behaviour on later PCRE2 releases, other Node versions and browsers, BSD/macOS grep and BusyBox was not run here; Java, .NET, PHP and Ruby are not covered. PCRE2 here is `grep -P`, which sets options of its own (for example UTF mode in a UTF-8 locale); a library embedding PCRE2 may differ.

Syntax Go rejects at regexp.Compile

Each error text was copied from a real regexp.Compile call on Go 1.24.7 (linux/amd64). Every message starts with `error parsing regexp: `, then the error code, a colon and the offending fragment in backticks. MustCompile panics with `regexp: Compile(` + the quoted pattern + `): ` + the same text.

Syntax Go rejects at regexp.Compile
SyntaxPattern triedregexp.Compile error (Go 1.24.7)Rewrite
Positive lookahead `(?=…)``foo(?=bar)``error parsing regexp: invalid or unsupported Perl syntax: `(?=``Capture the context: `foo(bar)` and read the groups. Or find `foo`, then test the rest with `strings.HasPrefix(s[end:], "bar")`.
Negative lookahead `(?!…)``foo(?!bar)``error parsing regexp: invalid or unsupported Perl syntax: `(?!``Find `foo`, then reject the match when the text after it starts with `bar`.
Positive lookbehind `(?<=…)``(?<=a)b``error parsing regexp: invalid named capture: `(?<=a)b```a(b)` and read group 1, or find `b` and inspect the rune before it. The message quotes everything from `(?<` to the end of the pattern.
Negative lookbehind `(?<!…)``(?<!a)b``error parsing regexp: invalid named capture: `(?<!a)b``Find `b`, then reject it when the preceding rune is `a` (retry one rune after a rejected start).
Atomic group `(?>…)``(?>a+)b``error parsing regexp: invalid or unsupported Perl syntax: `(?>``Drop the wrapper when it was only there for speed. It can change what matches (`(?>a*)a` never matches in Python 3.13 or `grep -P`, while `a*a` does), so port the intent, not the syntax.
Possessive quantifier `*+``a*+``error parsing regexp: invalid nested repetition operator: `*+``Use the plain quantifier. `a++` reports `++`, `a?+` reports `?+`, `a{2}+` reports `{2}+`, `a**` reports `**`; only `a*?` (lazy) is valid.
Backreference `\1``(a)\1``error parsing regexp: invalid escape sequence: `\1``Capture both pieces and compare in code: `(\w)(\w)` then `m[1] == m[2]`.
Backreference `\g1`, `\k<name>``(a)\g1`, `(?<x>a)\k<x>``error parsing regexp: invalid escape sequence: `\g`` and `error parsing regexp: invalid escape sequence: `\k``Same rewrite as `\1`: capture, then compare.
Named backreference `(?P=name)``(?P=n)``error parsing regexp: invalid or unsupported Perl syntax: `(?P``Same rewrite as `\1`: capture, then compare. `(?P>n)` (call) reports the same message.
Conditional `(?(1)a|b)``(?(1)a|b)``error parsing regexp: invalid or unsupported Perl syntax: `(?(``Spell out the two branches as an alternation, or branch on the match result in Go.
Recursion `(?R)`, `(?1)`, `(?&n)``(?R)``error parsing regexp: invalid or unsupported Perl syntax: `(?R`` (`(?1)` reports `(?1`, `(?&n)` reports `(?&`)Regular expressions cannot match nesting; use a parser or a depth counter.
Search anchor `\G``\G``error parsing regexp: invalid escape sequence: `\G``Loop on the remainder `s[pos:]` with a leading `^`.
Match reset `\K``foo\Kbar``error parsing regexp: invalid escape sequence: `\K```foo(bar)` and read group 1.
End anchor `\Z``\Z``error parsing regexp: invalid escape sequence: `\Z```\z` is end of text only; for "end, or before one final newline" write `\n?\z`.
Shorthands `\R`, `\h`, `\X`, `\N`, `\C``\R``error parsing regexp: invalid escape sequence: `\R`` (the others report `\h`, `\X`, `\N`, `\C`)`\R` becomes `(?:\r\n|[\n\v\f\r\x{85}\x{2028}\x{2029}])`, `\h` becomes `[ \t]`; `\X` (grapheme cluster) has no equivalent.
Control escapes `\cA`, `\e`, `[\b]``\e``error parsing regexp: invalid escape sequence: `\e`` (`\cA` reports `\c`, `[\b]` reports `\b`)Write the code point: `\x1b` (escape), `\x01` (Ctrl-A), `[\x08]` (backspace). `\a`, `\f`, `\t`, `\n`, `\r`, `\v` are valid.
Unicode escape `\uXXXX``\u0041``error parsing regexp: invalid escape sequence: `\u```\x{0041}`. Code points above `\x{10FFFF}` are also rejected (`\x{110000}` reports `\x{110000`).
Class as range end `[a-\d]``[a-\d]``error parsing regexp: invalid escape sequence: `\d``Put the class beside the range instead: `[a-z\d]`.
Extended mode `(?x)``(?x)a b``error parsing regexp: invalid or unsupported Perl syntax: `(?x``No verbose mode: build the pattern from commented string pieces joined with `+`, or a raw string per piece.
Inline comment `(?#…)``(?#note)a``error parsing regexp: invalid or unsupported Perl syntax: `(?#``Comment in Go source instead, next to the string piece.
Unknown flags `(?a)`, `(?u)`, `(?J)``(?a)``error parsing regexp: invalid or unsupported Perl syntax: `(?a`` (`(?u)` reports `(?u`, `(?J)` reports `(?J`)Only `i`, `m`, `s` and `U` exist. `\d`, `\w`, `\b` are already ASCII-only, so `(?a)` is the default behaviour.
Branch reset `(?|…)``(?|a)``error parsing regexp: invalid or unsupported Perl syntax: `(?|``Use distinct groups per branch and pick the non-empty one in code.
Quoted group name `(?'n'…)``(?'y'a)``error parsing regexp: invalid or unsupported Perl syntax: `(?'```(?P<y>a)` or `(?<y>a)`.
Bad group name`(?P<n!>a)``error parsing regexp: invalid named capture: `(?P<n!>`` (`(?<n-1>a)` reports `(?<n-1>`, `(?P<>a)` reports `(?P<>`)Group names are letters, digits and underscore only.
Repeat count above 1000`a{1001}``error parsing regexp: invalid repeat count: `{1001}```a{1000}`, or `a{1000}a`, or loop in Go. `a{1000}` and unbounded `a{1,}` compile; `a{2,1}` reports `{2,1}`.
Nested counted repeats`(?:a{500}){3}``error parsing regexp: invalid repeat count: `{3}``The product of nested counts must stay at or below 1000 (`(?:a{10}){10}` compiles). Flatten the pattern or use `+`.
Unknown Unicode property`\p{Foo}``error parsing regexp: invalid character class range: `\p{Foo}``Use a real script or category: `\p{Han}`, `\p{Greek}`, `\pL`, `\p{Nd}` compile.
Unknown POSIX class`[[:foo:]]``error parsing regexp: invalid character class range: `[:foo:]```[[:alpha:]]`, `[[:digit:]]`, `[[:^alpha:]]` are valid (ASCII only). `[[.a.]]` and `[[=a=]]` compile but are not collating elements.
Pattern too large`\pL{1000}` repeated 5000 times`error parsing regexp: expression too large: ` followed by the whole pattern in backticksSplit the work or shorten the pattern. Observed with 5000 copies of `\pL{1000}`; 1000 copies compiled.
Nesting too deep1000 `(` then 1000 `)``error parsing regexp: expression nests too deeply: ` followed by the pattern in backticksFlatten the grouping. 1000 nested groups were rejected on Go 1.24.7.

Accepted without error on Go 1.24.7: `(?P<y>a)`, `(?<y>a)` (the `(?<name>` form arrived in Go 1.22: Go 1.21.13 rejected it, Go 1.22.0 compiled it; the Go 1.22 release notes do not mention it), `(?i)`, `(?s)`, `(?m)`, `(?U)`, `\A`, `\z`, `\b`, `\B`, `\Q…\E`, `\p{Han}`, `\pL`, `\p{^L}`, `\P{L}`, `[[:alpha:]]`, `\x{10FFFF}`, `\123` (octal), `a{,3}` and `a{` (both are literal text). As of 2026-10; the Go source of regexp/syntax is the authority if a later release changes a message.

Go regexp functions and what they return

Method names are built from parts: Find, then optionally All, String, Submatch and Index in that order. The String variants take and return string; the others use []byte. Examples were run on Go 1.24.7 with `(\d{4})-(\d{2})(-(\d{2}))?`-style patterns.

Go regexp functions and what they return
FunctionReturnsWhen nothing matchesNotes
`MatchString(s)`, `Match(b)``bool``false`Cheapest check: 0 allocs/op in the benchmark. The package-level `regexp.MatchString(pat, s)` compiles the pattern on every call (37 allocs/op observed).
`FindString(s)`, `Find(b)`Text of the leftmost match`""` / `nil`An empty match and no match both give `""` for `FindString`; use the Index form to tell them apart.
`FindStringIndex(s)`, `FindIndex(b)``[]int{start, end}` byte offsets`nil``dateRe.FindStringIndex("on 2026-10 and 2026-10-11.")` → `[3 10]`. Offsets are bytes, not runes.
`FindStringSubmatch(s)`, `FindSubmatch(b)``[]string` of length `NumSubexp()+1`; element 0 is the whole match`nil`A group that did not take part is `""`: `(a)|(b)` on `b` → `["b" "" "b"]`.
`FindStringSubmatchIndex(s)`, `FindSubmatchIndex(b)``[]int` of length `2*(NumSubexp()+1)`: start, end pairs`nil`An unmatched group is `-1 -1`: `(a)|(b)` on `b` → `[0 1 -1 -1 0 1]`. The only form that separates "did not match" from "matched empty".
`FindAllString(s, n)`, `FindAll(b, n)``[]string` of all non-overlapping matches`nil``n < 0` all, `n > 0` at most `n`, `n == 0` returns `nil` (observed).
`FindAllStringIndex(s, n)`, `FindAllIndex(b, n)``[][]int` of start, end pairs`nil``a*` on `baaab` → `[[0 0] [1 4] [5 5]]`: an empty match right after the previous match is skipped.
`FindAllStringSubmatch(s, n)`, `FindAllSubmatch(b, n)``[][]string`, one row per match`nil`The usual choice for key/value extraction over many lines.
`FindAllStringSubmatchIndex(s, n)`, `FindAllSubmatchIndex(b, n)``[][]int`, one slice of offsets per match`nil`Full position information; the base for custom replace loops and for resuming a search after group 1.
`FindReaderIndex(r)`, `MatchReader(r)`Offsets, or `bool`, from an `io.RuneReader``nil` / `false`Scans a stream without loading it; first match only (`b+` on `aabbb` → `[2 5]`). There is no `All` form.
`ReplaceAllString(s, repl)`, `ReplaceAll(b, repl)`New string with every match replacedInput unchanged`$1`, `${1}`, `$name`, `${name}` expand; `$$` is a literal `$`; `\1` is not special. `$1_x` means the group named `1_x` and gives `""`.
`ReplaceAllLiteralString(s, repl)`New string, `repl` inserted verbatimInput unchanged`$2:$1` stays `$2:$1`. Use it when the replacement is data, not a template.
`ReplaceAllStringFunc(s, f)`, `ReplaceAllFunc(b, f)`New string; `f` maps the matched text to its replacementInput unchanged`f` receives only the whole match, never the groups; the result is not template-expanded.
`ExpandString(dst, template, src, match)`, `Expand(...)``dst` with the expanded template appended–`match` comes from a `...SubmatchIndex` call: template `$2 <- $1` on `bob@example.com` → `example <- bob`.
`Split(s, n)``[]string` between matches`[]string{s}`Trailing empties are kept: `,` on `a,b,,c,` → `["a" "b" "" "c" ""]`; `n > 0` limits the count (`n = 2` → `["a" "b,,c,"]`); `n == 0` gives `nil`.
`QuoteMeta(s)``s` with regex metacharacters escaped–Escapes `\.+*?()|[]{}^$`; leaves `-`, `_`, space and non-ASCII alone (`a.b*c[d]` → `a\.b\*c\[d\]`). A package function, not a method.
`NumSubexp()`, `SubexpNames()`, `SubexpIndex(name)`Group count; names slice with `""` at index 0 and for unnamed groups; index of a name`-1` for an unknown name`["" "year" "month" "" "day"]` for `(?P<year>…)-(?P<month>…)(-(?P<day>…))?`. With duplicate names `SubexpIndex` returns the leftmost.
`Longest()`, `CompilePOSIX(expr)`Switches the `Regexp` to leftmost-longest matching–`a|ab` on `ab` → `a` by default, `ab` after `Longest()` or with `MustCompilePOSIX`. `Longest` is a configuration method: call it before sharing the `Regexp` between goroutines.
`LiteralPrefix()`Literal prefix and whether it is the whole pattern`""`, `false``abc+d` → `abc`, `false`; `abc` → `abc`, `true`. A long literal prefix is what makes a search start fast.
`String()`, `MarshalText()`The source pattern text–`MarshalText` returns the same text as `String` (observed); the type implements `encoding.TextMarshaler`.

Index values are byte offsets into the input, so slice the original string with them (`s[loc[0]:loc[1]]`). All forms with `n` stop after `n` matches; pass -1 for no limit.

Backtracking red flags

Each row is a pattern you can paste into a test. The subject in brackets is n copies of a character plus the tail that makes the match fail. Cells were measured on Python 3.13.16, Node v22.22.0, Go 1.24.7 and GNU grep 3.11 (PCRE2 10.42). A ratio is the time against the input one step smaller (best of several runs); only trends are given, no absolute times.

Backtracking red flags
Pattern (subject)Why it is dangerousSafe rewritePython 3.13Node 22Go 1.24grep -P (PCRE2)
`^(a+)+$` (n × `a` + `b`)Nested quantifier: n letters split into runs in 2^(n-1) ways, all retried on failure`^a+$`exponential: about x4 per +2 characters (n = 16..28)exponential: about x4 per +2 characters (n = 16..30)linear: about x2 per doubling (n = 100,000..1,600,000)`exceeded PCRE's backtracking limit` from n = 23 (n = 22 answered 0)
`^(a|aa)+$` (n × `a` + `b`)Overlapping alternation: both branches consume `a`, so the number of splits grows like the Fibonacci numbers`^a+$`exponential: about x7 per +4 characters (n = 24..36)exponential: x6 to x9 per +4 characters (n = 24..36)linear: about x2 per doubling (n = 100,000..1,600,000)limit error from n = 33 (n = 32 answered 0)
`^(a|a)+$` (n × `a` + `b`)Identical branches: two ways to consume every letter`^a+$`exponential: x3.3 to x4.5 per +2 characters (n = 14..22)exponential: x3.0 to x4.1 per +2 characters (n = 14..22)linear: about x2 per doubling (n = 100,000..1,600,000)limit error from n = 23 (n = 22 answered 0)
`^(\w+\s?)*$` (n × `a` + `!`)Optional separator inside a repeated group: a word can end anywhere, so the same letters split many ways`^(?:\w+\s)*\w*$`exponential: x2.5 to x5.9 per +2 characters (n = 14..22)exponential: x2.7 to x4.1 per +2 characters (n = 14..22)linear: about x2 per doubling (n = 100,000..1,600,000)limit error from n = 22 (n = 20 answered 0)
`^(.*)*x$` (n × `a` + `xb`)A repeated group that can match everything or nothing`^.*x$`exponential: x3.7 to x6.5 per +2 characters (n = 14..22)exponential: x3.5 to x4.0 per +2 characters (n = 14..22)linear: about x2 per doubling (n = 100,000..1,600,000)limit error from n = 20 (n = 16 answered 0)
`^([\w.]+)*@example\.com$` (n × `a` + `!@example.com`)Nested quantifier in an email-like local part; the failure comes after the group, at `!``^[\w.]*@example\.com$`exponential: x2.8 to x4.6 per +2 characters (n = 14..22)exponential: x2.2 to x4.1 per +2 characters (n = 14..22)linear: about x2 per doubling (n = 100,000..1,600,000)limit error from n = 23 (n = 22 answered 0)
`\s+$` (n spaces + `x`)Quadratic: every start inside the run scans to its end before `$` failsTrim in code: `rstrip()`, `strings.TrimRight`, `trimEnd()`quadratic: x3.4 to x4.2 per doubling (n = 2,000..16,000)quadratic: x3.9 to x4.0 per doubling (n = 2,000..16,000)linear: about x2 per doubling (n = 100,000..1,600,000)no error up to n = 100,000 (answered 0)
`.*.*=.*` (n × `a`, no `=`)Adjacent `.*` on text with a missing literal: the splits multiply, cubic`=` for a contains test, `^[^=]*=` to anchor at the startcubic: x7.7 to x7.9 per doubling (n = 1,000..4,000)cubic: x8.3 to x8.4 per doubling (n = 2,000..4,000)linear: about x2 per doubling (n = 100,000..1,600,000)no error up to n = 20,000 (the required `=` is absent, so it fails at once)

As of 2026-10. The safe rewrites of the first six rows accept exactly the same strings as the originals on every string up to length 8 over a small alphabet (0 mismatches) and grew x2 per doubling on Python at n = 100,000..800,000. PCRE2 skips work when a required literal is missing from the subject, so the subjects above contain the pattern's literals; the match limit and its position depend on the PCRE2 build. `grep -E` is not a column: it stayed flat on the first row (800,000 characters).

Core syntax

What `.`, `\d`, `\w`, `\s` and `[...]` match in Go, Python, JavaScript and PCRE2, which characters need escaping inside and outside a class, and why `\d` is ASCII-only everywhere except Python.

The problem

A character class looks like the simplest part of a regex, yet the same `\d` or `.` selects different text in different engines, and the rules for what must be escaped change once you are inside `[...]`. The bugs are quiet: a validator that accepts Arabic-Indic digits in Python, a `.` that stops at `\r` in JavaScript, a `[\w-.]` that compiles in Go and fails in Python.

How it works

  • Shorthand classes: `\d` digits, `\w` word characters (`[A-Za-z0-9_]` in ASCII mode), `\s` whitespace, and the negations `\D \W \S`. Observed on Go 1.24, Node 22 and PCRE2 10.42: `\d+` on `x٣٤42` matches only `42`. Python 3.13 on a `str` pattern is Unicode-aware and matches `٣٤42`; `re.ASCII` or `[0-9]` restores the ASCII behavior.
  • `\w` follows the same split. Go, JavaScript and PCRE2 match `[A-Za-z0-9_]` only (`\w+` on `café` gives `caf`), Python matches letters and digits of any script (`café`, and `中文abc` as one run). For Unicode letters use `\p{L}` (Go, PCRE2, JavaScript with `u`), not `\w`.
  • `\s` differs in the corners. Go's `\s` is `[\t\n\f\r ]` and does not match a vertical tab or U+00A0. PCRE2 adds the vertical tab (`\x0B`) but not U+00A0. Python and JavaScript also match U+00A0 and spaces such as U+2003.
  • `.` matches any character except a line terminator. Go, Python and PCRE2 (newline = LF) exclude only `\n`; JavaScript also excludes `\r`, U+2028 and U+2029 (`.+` on `ab\rcd` matches `ab`, elsewhere the whole string). The `s` flag (dotAll) lets `.` match everything; `[\s\S]` does the same in every engine.
  • Inside `[...]`: `^` negates only as the first character, `-` is a range operator unless first or last, and `]` closes the class unless it comes first. `[]a]` matches `]` in Go, Python and PCRE2, but in JavaScript `[]` is an empty class that never matches. `[^]` is a compile error in Go, Python and PCRE2 and means "any character" in JavaScript.
  • A shorthand cannot be a range endpoint: `[\w-.]` compiles in Go and in JavaScript without `u` (hyphen literal) but fails in Python (`bad character range \w-. at position 1`) and PCRE2 (`invalid range in character class`), and in JavaScript with `u` or `v` (`Invalid character class`). Write `[\w.-]`. `[\d.]` works everywhere. `[\b]` is backspace in Python, JavaScript and PCRE2 and a compile error in Go (`invalid escape sequence: `\b``).
  • POSIX classes such as `[[:alpha:]]` work in Go and PCRE2; Python and JavaScript do not parse them as POSIX (`[[:alpha:]]+` on `ab1` finds nothing). Class subtraction like `[a-z&&[^b]]` is not supported by any of the four (only JavaScript's `v` flag has set operations, with `--` and `&&`).
  • Escaping outside a class: escape `\ . * + ? ( ) [ { | ^ $`. A bare `* + ? ( )` or `[` is a compile error in all four engines, while a bare `.`, `|`, `^` or `$` silently keeps its operator meaning. A bare `]` or `}` is literal, except in JavaScript with `u` or `v`, where both are errors (`Lone quantifier brackets`).
  • Unknown escapes: Go, Python and PCRE2 reject escaped ASCII letters they do not define (`\y` gives `invalid escape sequence: `\y``, `bad escape \y at position 0`, `unrecognized character follows \`); JavaScript without `u` quietly reads `\y` as `y` and `\e` as `e`. With `u`, `\-`, `\#`, `\ ` and `\&` outside a class are errors (`Invalid escape`).
  • Spelling a code point: `\x41` works in all four; `\x{41}` in Go and PCRE2 only; `\u{41}` in JavaScript with `u` only; the four-digit `\u` form (backslash, `u`, four hex digits) in Python and JavaScript only (Go and PCRE2 reject it). `\Q...\E` literal spans work in Go and PCRE2; PCRE2 also adds `\h`, `\R`, `\K`, `\e` (Go, Python: error; JavaScript: matches the plain letter).

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    const in = "x٣٤42 café"
    fmt.Printf("%q\n", regexp.MustCompile(`\d+`).FindString(in))
    fmt.Printf("%q\n", regexp.MustCompile(`\p{Nd}+`).FindString(in))
    fmt.Printf("%q\n", regexp.MustCompile(`\w+`).FindAllString(in, -1))
    fmt.Printf("%q\n", regexp.MustCompile(`[\p{L}\p{Nd}]+`).FindAllString(in, -1))
    fmt.Printf("%q\n", regexp.MustCompile(`[[:alpha:]]+`).FindString("ab1"))
    _, err := regexp.Compile(`[\b]`)
    fmt.Println(err)
}

// Output on Go 1.24:
// "42"
// "٣٤42"
// ["x" "42" "caf"]
// ["x٣٤42" "café"]
// "ab"
// error parsing regexp: invalid escape sequence: `\b`

Python: `\d` and `\w` are Unicode-aware by default; `re.ASCII` or an explicit range restores ASCII.

Python
import re

s = "x٣٤42"
print(re.findall(r"\d+", s))
print(re.findall(r"\d+", s, re.ASCII))
print(re.findall(r"[0-9]+", s))
print(re.findall(r"\w+", "café 中文"))
print(re.findall(r"\w+", "café 中文", re.ASCII))

# Output on Python 3.13:
# ['٣٤42']
# ['42']
# ['42']
# ['café', '中文']
# ['caf']

JavaScript: `\d` and `\w` are ASCII-only, `\s` includes U+00A0, and Unicode needs `\p{...}` with the `u` flag.

javascript
const s = "x٣٤42";
console.log(s.match(/\d+/g));
console.log(s.match(/\p{Nd}+/gu));
console.log("café 中文".match(/\w+/g));
console.log("café 中文".match(/[\p{L}\p{N}]+/gu));
console.log(/\s/.test("a\xa0b"), /\s/.test("a\xa0b".replace("\xa0", "")));

// Output on Node 22:
// [ '42' ]
// [ '٣٤42' ]
// [ 'caf' ]
// [ 'café', '中文' ]
// true false

In practice

  • Go regexp — RE2 syntax: `\d \w \s \b` are ASCII-only by design, Unicode needs `\p{...}`, `[[:alpha:]]` works, and `\Z`, `\h`, `\R` do not compile. Observed on Go 1.24.
  • Python re — `str` patterns use Unicode semantics for `\d \w \s \b` unless `re.ASCII` is set (observed on 3.13: `\d+` matches `٣٤`). `bytes` patterns are ASCII-only (observed: `rb'\w+'` on the UTF-8 bytes of `café` matches `caf`).
  • V8 Irregexp — ECMAScript rules: `.` stops at `\r`, U+2028 and U+2029, `\s` includes U+00A0, and without `u` unknown identity escapes are allowed (`\y` matches `y`). Observed on Node 22.22.
  • GNU grep -P — Uses PCRE2 10.42 here. In a UTF-8 locale `printf '\xd9\xa3\n' | grep -cP '\d'` prints `0`, while `\p{Nd}` prints `1`: `\d` stays ASCII-only, so the property escape is the Unicode spelling.
  • ripgrep — Rust regex semantics, a fifth engine this sheet does not tabulate: `\d` is Unicode-aware by default (`echo 'x٣٤' | rg -o '\d+'` prints `٣٤`) and `(?-u)\d+` restores ASCII. Observed on rg 14.1.0.

Trade-offs

Pros

  • Shorthand classes are short and, for ASCII input, behave the same in every engine.
  • Explicit ranges such as `[0-9]` and `[A-Za-z]` mean the same thing everywhere, including Python.
  • The set of characters that need escaping is the same twelve in all four engines, so one `QuoteMeta`-style function is portable.

Cons

  • `\d \w \s \b` are not portable for non-ASCII text: Python is Unicode-aware, the other three are not.
  • Leniency hides typos: a bare `{` or `]` compiles outside JavaScript's `u` mode, and JavaScript without `u` accepts `\y`.
  • Class-internal corner cases (`[]a]`, `[^]`, `[\w-.]`, POSIX classes) differ, so a pattern that compiles in one engine may fail in another.

`* + ? {n,m}` with the lazy `?` and possessive `+` suffixes: why `.*` overshoots, what each engine does with `a*+`, `{,n}` and huge counts, and what a lazy quantifier costs.

The problem

A quantifier says how many times the previous item repeats, and the default is "as many as possible". That default is why `<.+>` swallows `<a><b>` whole, why one stray `.*` turns a field extractor into a line grabber, and why the same quantifier syntax is a feature in one engine and a compile error in another.

How it works

  • Basic forms: `*` zero or more, `+` one or more, `?` zero or one, `{n}`, `{n,}`, `{n,m}`. All are greedy: take as many repetitions as possible, then give them back one at a time if the rest of the pattern fails. Observed in all four engines: `a{2,4}` on `aaaaa` gives `aaaa`, `a{3,}` gives `aaaaa`, `a{3}` gives `aaa`.
  • Lazy forms add `?`: `*?`, `+?`, `??`, `{n,m}?`. Lazy takes as few repetitions as possible and extends one at a time only when the rest fails. `<.+?>` on `<a><b>` gives `<a>` in all four engines (greedy `<.+>` gives `<a><b>`); `a{2,4}?` on `aaaaa` gives `aa`.
  • When the stop character is known, prefer a negated class: `<[^>]+>` gives `<a>` in all four engines, cannot run past the delimiter, and does not depend on how the engine orders its backtracking.
  • Lazy is not "faster". Against a tail `(\d+)$` on `"1" * n + "x"`, both `^.*?(\d+)$` and `^.*(\d+)$` took about four times as long each time n doubled on Python 3.13 and Node 22 (quadratic), while `^[^\d]*(\d+)$` grew about twice (linear). Go 1.24 grew roughly linearly for both. Greedy and lazy only change which match wins, not how often the tail is retried.
  • Possessive forms `a*+`, `a++`, `a?+`, `a{1,3}+` never give repetitions back: `a*+a` can never match `aaa`. Accepted by Python 3.11+ and PCRE2; Go fails with `invalid nested repetition operator: `*+``; JavaScript fails with `Nothing to repeat`. In Go and JavaScript a stray `+` after a quantifier is therefore an error rather than a silent possessive.
  • Stacked quantifiers are errors in all four engines, each with its own message: `a**` gives `invalid nested repetition operator: `**`` (Go), `multiple repeat at position 2` (Python), `Nothing to repeat` (JavaScript), `quantifier does not follow a repeatable item` (PCRE2). Only a single lazy `?` suffix is legal. A leading `*a` is an error everywhere (`missing argument to repetition operator: `*`` in Go).
  • Counted-repeat limits: Go caps counts at 1000 (`a{1000}` compiles, `a{1001}` gives `invalid repeat count: `{1001}``) and nested counts multiply, so `(a{1000}){2}` fails with `invalid repeat count: `{2}``. PCRE2 10.42 caps at 65535 (`a{65536}` gives `number too big in {} quantifier`). Python and JavaScript compiled `a{65536}` and `a{100000}`.
  • `{,n}` is shorthand for `{0,n}` in Python only among the four tabulated engines: `a{,3}` fully matches `aaa` in Python, while Go, JavaScript and PCRE2 10.42 read it as the literal text `a{,3}` (PCRE2 10.43+ and Perl 5.34+ read it as `{0,n}`; not run here). A brace that is not a valid quantifier (`a{`, `a{1, 3}` with a space) is literal text in all four (JavaScript without `u`).

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    const html = "<a><b>"
    fmt.Println(regexp.MustCompile(`<.+>`).FindString(html))
    fmt.Println(regexp.MustCompile(`<.+?>`).FindString(html))
    fmt.Println(regexp.MustCompile(`<[^>]+>`).FindString(html))
    fmt.Println(regexp.MustCompile(`(?U)<.+>`).FindString(html))
    for _, p := range []string{`a{1000}`, `a{1001}`, `(a{1000}){2}`, `a*+`, `a**`, `a{3,2}`} {
        _, err := regexp.Compile(p)
        fmt.Printf("%-12s %v\n", p, err)
    }
}

// Output on Go 1.24:
// <a><b>
// <a>
// <a>
// <a>
// a{1000}      <nil>
// a{1001}      error parsing regexp: invalid repeat count: `{1001}`
// (a{1000}){2} error parsing regexp: invalid repeat count: `{2}`
// a*+          error parsing regexp: invalid nested repetition operator: `*+`
// a**          error parsing regexp: invalid nested repetition operator: `**`
// a{3,2}       error parsing regexp: invalid repeat count: `{3,2}`

Python: `{,n}` means `{0,n}`, possessive `*+` is accepted (3.11+), stacked quantifiers are an error.

Python
import re

print(re.fullmatch(r"a{,3}", "aaa") is not None)
print(re.fullmatch(r"a{,3}", "a{,3}") is not None)
print(re.search(r"a*+b", "aaab").group())
try:
    re.compile(r"a**")
except re.error as e:
    print(e)

# Output on Python 3.13:
# True
# False
# aaab
# multiple repeat at position 2

In practice

  • Go regexp — RE2-based: the repeat cap of 1000 is checked at compile time, and matching time stays linear in the input whichever of greedy or lazy is used (on Go 1.24 the time grew roughly in proportion to input length from 20k to 160k characters; trend only).
  • Python re — Python 3.11 added possessive quantifiers and atomic groups (per the changelog); `{,n}` is a shorthand that Go, JavaScript and PCRE2 10.42 read as literal text (PCRE2 10.43+ differs).
  • GNU grep -P — PCRE2 with a match limit: `grep -cP '^(a+)+$'` on 30 `a` followed by `c` printed `grep: <file>: exceeded PCRE's backtracking limit` instead of hanging, while the possessive form `^(?>a+)+$` printed `0` at once.
  • V8 Irregexp — No possessive syntax; `a++` is `Nothing to repeat`. Backtracking cost shows up as time: `^(a+)+$` on `a`s plus a trailing `c` grew about four times per two extra characters (trend only, n = 18 to 24).

Trade-offs

Pros

  • The greedy default returns the longest candidate, which is what most field and number extractors want.
  • Lazy quantifiers and negated classes give a cheap way to stop at the first delimiter.
  • Possessive quantifiers, where supported, remove backtracking and make failure fast.

Cons

  • Greedy `.*` overshoots across delimiters on a single line and is the usual cause of "matched too much".
  • Lazy quantifiers do not cut the worst-case cost; they only change which match wins.
  • Possessive quantifiers and `{,n}` are not portable (`{,n}` differs even between PCRE2 versions), and Go caps repeat counts at 1000.

`^ $ \A \z \Z \b \B`: how multiline mode changes `^` and `$`, why `$` accepts a trailing newline in Python and PCRE2, which engines have `\A`, `\z` and `\Z`, and what `\b` means for non-ASCII text.

The problem

Validators and extractors depend on where a match may begin and end. `^\d+$` accepts `"12\n"` in Python and PCRE2 but rejects it in Go and JavaScript, and `caf\b` is a boundary inside `café` in Go and JavaScript but not in Python. Anchors are zero-width, so a mistake changes where the match lands rather than what it contains, and tests with clean input never notice.

How it works

  • Without flags, `^` is the start of the input and `$` is the end of the input. Go and JavaScript treat only the very end as `$`; Python and PCRE2 also let `$` match just before a final `\n`. Observed for `^\d+$` on `12\n`: Go no match, JavaScript no match, Python matches `12`, PCRE2 10.42 (default options) matches `12`.
  • `grep -P` sets PCRE2's DOLLAR_ENDONLY, so it behaves like Go here: `printf '12\n' | grep -zcP '^\d+$'` prints `0`, while `^\d+\Z` prints `1`. The PCRE2 column on this sheet is the library with default options, not `grep -P`.
  • Absolute anchors: `\A` is the start in Go, Python and PCRE2 (in JavaScript it is an identity escape that matches the letter `A`). `\z` is the absolute end in Go and PCRE2; Python 3.13 rejects it (`bad escape \z at position 3`). `\Z` means "end, or before a final newline" in Python and PCRE2 and is a compile error in Go (`invalid escape sequence: `\Z``).
  • Portable "whole string" checks: Python `re.fullmatch`, Go and JavaScript `^...$` without the `m` flag, PCRE2 `\A...\z`. `re.fullmatch(r"\d+", "12\n")` is `None`, `re.search(r"^\d+$", "12\n")` is a match.
  • Multiline mode (`m`) makes `^` and `$` also match at line breaks: `^\d+$` on `12\n\n` matches in all four only with `m`. `$` on `a\n` finds positions 1 and 2 with `m` everywhere; without `m`, Python still finds both (1 and 2) while Go and JavaScript find only 2.
  • What counts as a line break differs: Go, Python and PCRE2 (LF build) use `\n` only; JavaScript also uses `\r`, U+2028 and U+2029. With `m`, `a$` matches in `a\r\nb` and `^b` matches in `a\rb` only in JavaScript.
  • `\b` sits between a word and a non-word character (or an edge); `\B` is its negation; neither consumes a character. Because `\w` is ASCII in Go, JavaScript and PCRE2, `caf\b` matches inside `café` there; in Python `\b` is Unicode-aware and `caf\b` does not match. JavaScript's `u` flag does not change `\b` (`/\bé/u` on `é` is false); PCRE2 gets Unicode word boundaries from `(*UTF)(*UCP)`; Go has no switch.
  • Empty input: `\b` never matches the empty string; `\B` matches it in Go, JavaScript and PCRE2, but `re.search(r"\B", "")` is `None` on Python 3.13. A `^` or `$` in the middle (`a^b`, `a$b`) never matches, even with `m`.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    digits := regexp.MustCompile(`^\d+$`)
    fmt.Println(digits.MatchString("12"), digits.MatchString("12\n"))
    lines := regexp.MustCompile(`(?m)^\d+$`)
    fmt.Println(lines.FindAllString("12\n34\n", -1))
    whole := regexp.MustCompile(`\A\d+\z`)
    fmt.Println(whole.MatchString("12\n"))
    _, err := regexp.Compile(`\d+\Z`)
    fmt.Println(err)
    word := regexp.MustCompile(`caf\b`)
    fmt.Println(word.MatchString("café"))
}

// Output on Go 1.24:
// true false
// [12 34]
// false
// error parsing regexp: invalid escape sequence: `\Z`
// true

Python: `$` accepts a trailing newline, `fullmatch` and `\Z` do not, `\b` is Unicode-aware, `\z` is rejected on 3.13.

Python
import re

print(bool(re.search(r"^\d+$", "12\n")))
print(bool(re.fullmatch(r"\d+", "12\n")))
print(bool(re.search(r"^\d+\Z", "12\n")))
print(bool(re.search(r"\bcaf\b", "café")))
print(re.findall(r"^\w+$", "ab\ncd\n", re.M))
try:
    re.compile(r"\d+\z")
except re.error as e:
    print(e)

# Output on Python 3.13:
# True
# False
# False
# False
# ['ab', 'cd']
# bad escape \z at position 3

JavaScript: `$` is strict, `m` also splits on `\r`, `\b` is ASCII-only even with `u`, and `\A`/`\z` do not exist (they match the letters `A` and `z`).

javascript
console.log(/^\d+$/.test("12\n"));
console.log(/^\d+$/m.test("12\r\n"));
console.log(/caf\b/.test("café"));
console.log(/\bé/u.test("é"));
console.log("ab\ncd\n".match(/^\w+$/gm));
console.log(/\Aa/.test("a"), /a\z/.test("a"));

// Output on Node 22:
// false
// true
// true
// false
// [ 'ab', 'cd' ]
// false false

In practice

  • Python re — `re.match` anchors at the start implicitly and `re.fullmatch` at both ends (since 3.4), which is the call to use for validation because `$` accepts a trailing newline. Observed on 3.13.
  • GNU grep -P — PCRE2 10.42 with DOLLAR_ENDONLY set and no MULTILINE under `-z`; `printf 'a\nb' | grep -zcP '^b'` prints `0` because `^` only matches at the start of the NUL-separated record.
  • Go regexp — `$` without `(?m)` is the absolute end, so `MatchString("12\n")` is false for `^\d+$`; `\A` and `\z` exist, `\Z` does not. `(?m)^\d+$` finds `12` and `34` in `12\n34\n`. Observed on Go 1.24.
  • V8 Irregexp — The `m` flag treats `\r`, U+2028 and U+2029 as line terminators besides `\n`; there is no `\A` or `\z`. Observed on Node 22.22.

Trade-offs

Pros

  • Anchors make a pattern say exactly where it applies, which is what separates validation from search.
  • `\b` stops `cat` from matching inside `concatenate` for ASCII text without any lookaround.
  • `m` turns one pattern into a per-line scanner for logs and config files.

Cons

  • The trailing-newline behaviour of `$` (Python, PCRE2) lets values such as `"admin\n"` through a validator.
  • `\b` is wrong for non-ASCII words in Go, JavaScript and PCRE2 without extra options, and only Python gets it right by default.
  • `\A`, `\z`, `\Z` are available in different subsets of the engines, so only `^...$` without `m` is close to portable.

Capturing `( )`, non-capturing `(?: )`, the three named-group spellings, group numbering, how `|` picks a branch, and what a group inside a quantifier remembers.

The problem

Groups do three jobs at once: they scope an alternation or a quantifier, they capture text for reuse, and they are the only handle a replacement or backreference has on a match. Mixing those jobs produces capture indexes that shift when someone adds a group, `^a|b$` anchoring only half the pattern, and named groups that run in Python but not in JavaScript.

How it works

  • Numbering follows the opening parenthesis, left to right, nested groups included: `((a)(b(c)))` on `abc` gives `abc`, `abc`, `a`, `bc`, `c` in all four engines. `(?:...)` is not counted, and named groups are numbered too (`(a)(?P<n>b)(c)` gives `a`, `b`, `c`). Adding a capturing group shifts every later index, so prefer names or `(?:...)`.
  • Named-group spellings, as observed: `(?P<n>...)` in Go, Python and PCRE2; `(?<n>...)` in Go, JavaScript and PCRE2 (Python: `unknown extension ?<n at position 1`); `(?'n'...)` only in PCRE2. JavaScript rejects `(?P<n>...)` with `Invalid group`. Backreference by name: `(?P=n)` in Python and PCRE2, `\k<n>` in JavaScript and PCRE2, nothing in Go.
  • Name rules differ. Go accepted `(?P<1a>a)` but rejected `a-b` and `é`; Python needs an identifier (`bad character in group name '1a'`) and accepts `é` with `(?P<é>...)`; PCRE2 requires a non-digit start (`subpattern name must start with a non-digit`). Duplicates: Python fails (`redefinition of group name 'y' as group 2; was group 1`), PCRE2 fails unless `(?J)` is set (`two named subpatterns have the same name (PCRE2_DUPNAMES not set)`), Node 22 fails even across alternatives (`Duplicate capture group name`), Go 1.24 compiled `(?P<y>a)(?P<y>b)` and `SubexpIndex("y")` returned 1.
  • `(?:...)` groups without capturing: no renumbering, no copy of the text. Scoped flag groups `(?i:...)` are non-capturing too.
  • Alternation `|` has the lowest precedence: `^a|b$` means `(^a)|(b$)` and matches `xb`, while `^(?:a|b)$` does not. Branch choice is leftmost-first in all four engines: `a|ab` on `ab` gives `a`, `ab|a` gives `ab`. POSIX ERE picks the longest instead (`echo ab | grep -oE 'a|ab'` prints `ab`, `grep -oP` prints `a`); Go gets that with `Longest()` or `CompilePOSIX` (both gave `ab`).
  • A group inside a quantifier keeps the last iteration: `(a|b)+` on `ab` gives group 1 `b` everywhere. Whether a group that did not take part in the last iteration is cleared differs: `(?:(a)|b)+` on `ab` gives group 1 `a` in Go, Python and PCRE2 but `undefined` in JavaScript, and `(a*)*` on `b` gives an empty group 1 in Go, Python and PCRE2 but `undefined` in JavaScript.
  • Backreferences: `\1` works in Python, JavaScript and PCRE2; Go fails to compile (`invalid escape sequence: `\1``). A reference to a group that did not participate matches the empty string in JavaScript (`(a)|b\1` on `b` matches `b`) and fails in Python and PCRE2; a forward reference `\1(a)` matches `a` in JavaScript, is an error in Python (`invalid group reference 1`) and does not match in PCRE2. PCRE2 also accepts `\g1`, `\g{-1}`.
  • PCRE2 extras: branch reset `(?|(a)|(b))` (one group number for both branches), `(?n)` (only named groups capture: `(?n)(a)(?<x>b)` on `ab` gives group 1 `b`), and the comment group `(?#...)` which Python also accepts; Go and JavaScript reject `(?#`. Unmatched groups come back as `""` from Go's `FindStringSubmatch` but as `-1` from the `Index` variants, so use the latter to tell empty from absent.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    re := regexp.MustCompile(`(?P<year>\d{4})-(?<month>\d{2})-(\d{2})`)
    fmt.Println(re.NumSubexp(), re.SubexpNames())
    m := re.FindStringSubmatch("on 2026-10-11.")
    fmt.Printf("%q\n", m)
    fmt.Println(m[re.SubexpIndex("month")])
    last := regexp.MustCompile(`(?:(a)|(b))+`).FindStringSubmatch("ab")
    fmt.Printf("%q\n", last)
    _, err := regexp.Compile(`(a)\1`)
    fmt.Println(err)
}

// Output on Go 1.24:
// 3 [ year month ]
// ["2026-10-11" "2026" "10" "11"]
// 10
// ["ab" "a" "b"]
// error parsing regexp: invalid escape sequence: `\1`

Python: `(?P<name>...)`, `groupdict()`, captures kept from earlier iterations, and the `(?<name>...)` error.

Python
import re

m = re.search(r"(?P<y>\d{4})-(?P<m>\d\d)", "2026-10")
print(m.groupdict(), m.group("y"), m[2])
print(re.search(r"(?:(a)|b)+", "ab").groups())
print(re.search(r"(a)|b\1", "b"))
try:
    re.compile(r"(?<y>\d{4})")
except re.error as e:
    print(e)

# Output on Python 3.13:
# {'y': '2026', 'm': '10'} 2026 10
# ('a',)
# None
# unknown extension ?<y at position 1

JavaScript: `(?<name>...)` with a `groups` object, captures reset per iteration, a backreference to a missing group matches empty, `(?P<...>)` is invalid.

javascript
const m = /(?<y>\d{4})-(?<m>\d\d)/.exec("2026-10");
console.log({ ...m.groups }, m.groups.y, m[2]);
console.log(/(?:(a)|b)+/.exec("ab"));
console.log(/(a)|b\1/.exec("b"));
try {
  new RegExp("(?P<y>\\d{4})");
} catch (e) {
  console.log(e.message);
}

// Output on Node 22:
// { y: '2026', m: '10' } 2026 10
// [ 'ab', undefined, index: 0, input: 'ab', groups: undefined ]
// [ 'b', undefined, index: 0, input: 'b', groups: undefined ]
// Invalid regular expression: /(?P<y>\d{4})/: Invalid group

In practice

  • Go regexp — `SubexpNames` and `SubexpIndex` map names to indexes; both `(?P<n>)` and `(?<n>)` compile on Go 1.24 (the second form was added in Go 1.22 per the Go issue tracker, CL 513838, and is not in the 1.22 release notes; not run on 1.22). `Longest()` switches to leftmost-longest.
  • Python re — `Match.groupdict()` and `m["name"]` expose named groups; only `(?P<n>)` is accepted, `(?<n>)` is `unknown extension ?<n`. Conditionals test a group number or name (see conditionals-recursion).
  • V8 Irregexp — ECMAScript 2018 named groups: `(?<n>)` with `m.groups.n`, `\k<n>` for references; captures inside a quantified group are reset each iteration, which differs from the other three. Observed on Node 22.22.
  • GNU grep -E — POSIX ERE has no `(?:...)` and no named groups, and alternation is leftmost-longest: `echo ab | grep -oE 'a|ab'` printed `ab`. `grep -P` is the PCRE2 route to `(?:...)`.

Trade-offs

Pros

  • Named groups survive refactoring: adding a group no longer breaks code that reads `m.groups.year`.
  • Non-capturing groups give scope for `|` and quantifiers without costing a capture slot.
  • Leftmost-first alternation is predictable: order the branches from most specific to least.

Cons

  • Three spellings for named groups (`?P<`, `?<`, `?'`) mean no single form is portable across all four engines.
  • Numbered captures shift silently when a group is added or removed.
  • Quantified captures behave differently in JavaScript, and Go has no backreferences at all.

`i m s x u g y d v` in JavaScript, `re.I re.M re.S re.X re.A` in Python, `(?imsU)` in Go and PCRE2: which flags exist where, inline-flag scope rules, and JavaScript's stateful `lastIndex`.

The problem

Flags change what a pattern means, and every engine spells them differently: JavaScript puts letters after the closing slash, Python has module constants and inline groups, Go and PCRE2 have only inline groups. A mid-pattern `(?i)` works in two engines and is an error in the other two, `x` does not exist in Go or JavaScript, `U` means "ungreedy" rather than "Unicode", and a JavaScript regex with `g` or `y` carries state between calls.

How it works

  • Core trio `i m s` (ignore case, multiline `^$`, dot matches newline) exists in all four: JavaScript `/i /m /s` (`s` since ES2018), Python `re.I re.M re.S` or `(?ims)`, Go and PCRE2 `(?ims)`. Node 22 has no inline flags at all: `(?i:a)b` fails with `Invalid group`.
  • Inline scope: in Go and PCRE2 `(?i)` applies to the rest of the enclosing group (`(a(?i)b)c` does not match `aBC` because `c` is outside the flag's scope), `(?i:...)` limits it to one group and `(?-i:...)` turns it off. Python 3.13 requires global flags at the very start (`a(?i)b` fails with `global flags not at the start of the expression at position 1`); use the scoped `(?i:...)` form, and note that a bare `(?-i)` is `missing :`.
  • `x` (verbose) exists in Python (`re.X`, `(?x)`) and PCRE2 (`x`, `xx`): unescaped whitespace and `#` comments outside classes are ignored. Space inside `[ ]` stays significant in Python and PCRE2 `x`; PCRE2 `xx` also drops it (`(?xx)[a b]+` on `a b` gives `a`). Go (`(?x` gives `invalid or unsupported Perl syntax: `(?x``) and JavaScript have no `x`; build the pattern from commented string pieces instead.
  • `U` in Go and PCRE2 is "ungreedy": it swaps greedy and lazy (`(?U)a+` on `aaa` gives `a`, `(?U)a+?` gives `aaa`). It is not a Unicode switch, and Python and JavaScript have no equivalent.
  • Unicode switches: JavaScript `u` (and `v`) turn on code-point semantics and strict escapes (`/^.$/u` matches one emoji, `/^.$/` does not; `[😀-🙏]` without `u` fails with `Range out of order in character class`); `v` adds set operations such as `[\p{L}--[a-z]]` and cannot be combined with `u` (`Invalid flags supplied to RegExp constructor 'uv'`). Python `str` patterns are Unicode by default; `re.ASCII` / `(?a)` restricts `\w \d \s \b` and case folding to ASCII (`(?i)k` matches the Kelvin sign U+212A, `(?ai)k` does not); `re.UNICODE` is a no-op for `str`, `re.LOCALE` is an error for `str`. Go is always UTF-8. PCRE2 needs `(*UTF)` and `(*UCP)` (or the PCRE2_UTF option); `grep -P` enables UTF in UTF-8 locales.
  • JavaScript `g` and `y` make the regex object stateful through `lastIndex`. Reusing `const g = /a/g` on `"aa"` gives `true` (lastIndex 1), `true` (2), `false` (0); a sticky `/a/y` with `lastIndex = 1` matches `ba` at index 1 and moves `lastIndex` to 2. `"aa".replaceAll(/a/, "b")` throws `String.prototype.replaceAll called with a non-global RegExp argument`.
  • Global and sticky are not flags elsewhere. Python picks by function (`re.findall` and `re.sub` are global, `count=` limits `sub`; `pattern.match(s, pos)` is the sticky form); Go uses `FindAll*(s, -1)` and `ReplaceAll*`; PCRE2 callers loop or set a substitute-global option, and the `\G` anchor exists (compiles; offset behaviour per the docs).
  • JavaScript `d` (hasIndices) adds `m.indices`: `/(?<n>b)/d.exec("abc")` gives `indices[0]` = `[1, 2]` and `indices.groups.n` = `[1, 2]`. Python's `m.span()`, `m.start(n)` and Go's `...Index` functions need no flag. Python flag values observed: `re.I`=2, `re.M`=8, `re.S`=16, `re.X`=64, `re.A`=256, `re.U`=32, `re.L`=4; `re.A | re.U` fails with `ASCII and UNICODE flags are incompatible`.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    fmt.Println(regexp.MustCompile(`(?i)hello`).MatchString("HeLLo"))
    fmt.Println(regexp.MustCompile(`(?s)a.b`).MatchString("a\nb"))
    fmt.Printf("%q\n", regexp.MustCompile(`(?m)^\w+`).FindAllString("ab cd\nef", -1))
    fmt.Println(regexp.MustCompile(`a(?i:b)c`).MatchString("aBc"), regexp.MustCompile(`a(?i:b)c`).MatchString("aBC"))
    fmt.Println(regexp.MustCompile(`(?U)a+`).FindString("aaa"))
    _, err := regexp.Compile(`(?x) a b `)
    fmt.Println(err)
    // No x flag: build readable patterns by concatenation.
    date := regexp.MustCompile(
        `^(\d{4})` + // year
            `-(\d{2})` + // month
            `-(\d{2})$`, // day
    )
    fmt.Println(date.MatchString("2026-10-11"))
}

// Output on Go 1.24:
// true
// true
// ["ab" "ef"]
// true false
// a
// error parsing regexp: invalid or unsupported Perl syntax: `(?x`
// true

Python: `re.M`, `re.S`, `re.X` with comments, scoped `(?i:...)`, and the error for a mid-pattern global flag.

Python
import re

print(re.findall(r"^\w+", "ab cd\nef", re.M))
print(re.search(r"a.b", "a\nb", re.S) is not None)
pat = re.compile(
    r"""
    ^(\d{4})   # year
    -(\d{2})   # month
    $
    """,
    re.X,
)
print(pat.match("2026-10").groups())
print(re.search(r"a(?i:b)c", "aBc") is not None)
try:
    re.compile(r"a(?i)b")
except re.error as e:
    print(e)
print(re.search(r"(?i)a(?-i:b)", "AB"))

# Output on Python 3.13:
# ['ab', 'ef']
# True
# ('2026', '10')
# True
# global flags not at the start of the expression at position 1
# None

JavaScript: `lastIndex` state with `g` and `y`, the `d` flag, and the `replaceAll` non-global error.

javascript
const g = /a/g;
console.log(g.test("aa"), g.lastIndex);
console.log(g.test("aa"), g.lastIndex);
console.log(g.test("aa"), g.lastIndex);
const y = /a/y;
y.lastIndex = 1;
console.log(y.test("ba"), y.lastIndex);
const d = /(?<n>b)/d.exec("abc");
console.log(d.indices[0], d.indices.groups.n);
console.log("aXbxc".split(/x/i));
try {
  "aa".replaceAll(/a/, "b");
} catch (e) {
  console.log(e.message);
}

// Output on Node 22:
// true 1
// true 2
// false 0
// true 2
// [ 1, 2 ] [ 1, 2 ]
// [ 'a', 'b', 'c' ]
// String.prototype.replaceAll called with a non-global RegExp argument

In practice

  • V8 Irregexp — Flags `d g i m s u v y`; `/a/dgimsuy.flags` printed `dgimsuy`, and an unknown or repeated flag throws `Invalid flags supplied to RegExp constructor 'gg'`. Observed on Node 22.22.
  • Python re — Flags are constants (`re.I`, `re.A`, `re.NOFLAG` since 3.11) or an inline group at the very start; `re.VERBOSE` is the usual way to comment a long pattern.
  • Go regexp — Only `i`, `m`, `s`, `U` exist as inline flags; `(?x`, `(?a`, `(?u`, `(?L` and `(?g` were all rejected with `invalid or unsupported Perl syntax`. Observed on Go 1.24.
  • PCRE2 — Adds `(?J)` (duplicate names), `(?n)` (no auto-capture), `xx`, and the `(*UTF)`/`(*UCP)` start-of-pattern verbs. Observed through libpcre2-8 10.42, the library behind `grep -P`.

Trade-offs

Pros

  • Inline flags make a pattern self-contained, which matters when it is stored in config, a WAF rule or a database column that cannot carry separate options.
  • Scoped groups such as `(?i:...)` limit case-insensitivity to the part that needs it.
  • Python's `re.VERBOSE` and PCRE2's `x` allow comments and layout in long patterns.

Cons

  • No spelling works in all four engines, and JavaScript has no inline flags at all.
  • `g` and `y` make JavaScript regexes stateful, so a shared regex object can alternate between `true` and `false`.
  • `U` means ungreedy in Go and PCRE2, and `u` means Unicode in JavaScript; copying a flag between engines changes meaning.

Advanced syntax

`(?=) (?!) (?<=) (?<!)` are zero-width assertions: the lookbehind length rules per engine, why Go has none at all, and the capture-group and two-step rewrites.

The problem

Lookarounds test the text around a position without consuming it: digits followed by a unit, a price preceded by `$`, a password that must contain several kinds of character. They need a backtracking engine, so Go and Rust (RE2-style) engines reject them, and the backward-looking forms have engine-specific length rules.

How it works

  • Four forms: `(?=X)` the text ahead matches X, `(?!X)` it does not, `(?<=X)` the text behind matches X, `(?<!X)` it does not. They are zero-width: `foo(?=bar)` on `foobar` matches only `foo`. Python, JavaScript and PCRE2 support all four.
  • Go rejects all four at compile time. Lookahead gives `invalid or unsupported Perl syntax: `(?=`` (and `(?!`); lookbehind gives `invalid named capture: `(?<=\$)\d+``, because Go 1.24 reads `(?<` as the start of a named group, so the message talks about names rather than lookbehind.
  • Lookbehind length rules, as observed. Python 3.13 needs a fixed width: `(?<=a+)b` gives `look-behind requires fixed-width pattern`, and so does `(?<=a|bc)x`, while equal-length alternatives `(?<=ab|cd)x` are fine. PCRE2 10.42 needs each top-level alternative to be fixed length but lets them differ (`(?<=a|bc)x` works; `a+`, `ab?`, `a{1,3}` give `lookbehind assertion is not fixed length`). V8 accepts any length, including `a+` and `a*`, and `(?<=(a|bc))x` captures `bc`.
  • Text captured inside a lookahead is kept: `(?=(\d+))\d` on `123` gives groups `1` and `123` in Python, JavaScript and PCRE2. A lookahead that captures and re-matches finds overlapping occurrences: `(?=(aa))` on `aaaa` matches at 0, 1 and 2.
  • Classic uses give identical results in Python, JavaScript and PCRE2: thousands separators `\B(?=(?:\d{3})+(?!\d))` turn `1234567` into `1,234,567`; and `^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$` accepts `Passw0rdX` and rejects `password1`, because every lookahead restarts from the same position.
  • PCRE2 has `\K`, which resets the reported match start: `foo\Kbar` on `foobar` reports `bar` (`grep -oP 'foo\Kbar'` prints `bar`), a cheap substitute for a variable-length lookbehind. Python rejects it (`bad escape \K`), Go rejects it (`invalid escape sequence`), JavaScript reads it as the letter `K`.
  • Rewrites for Go: put the context into a capture group (`\$(\d+)` and read `m[1]`), or find the candidate first and test the neighbouring bytes in code. The group rewrite consumes the context: `a(?=a)` on `aaa` matches at offsets 0 and 1 in Python, JavaScript and `grep -boP`, but Go's `(a)a` finds one match covering `aa` and resumes at offset 2. Details and trade-offs are in lookaround-rewrites-in-go.
  • Beyond the four tabulated engines: ripgrep's default Rust regex engine rejects lookaround (`rg 'foo(?=bar)'` prints `look-around, including look-ahead and look-behind, is not supported`), and `rg -P` or `--engine auto` switches to PCRE2. The third-party Python `regex` package (2026.9.29, installed here) accepted the variable-length `(?<=a+)b` that `re` rejects.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    // PCRE/JS: (?<=\$)\d+ -- Go rejects the lookbehind at compile time.
    _, err := regexp.Compile(`(?<=\$)\d+`)
    fmt.Println(err)
    // Rewrite 1: consume the context and read it back from a capture group.
    price := regexp.MustCompile(`\$(\d+)`)
    for _, m := range price.FindAllStringSubmatch("cost $42, $7 and 9", -1) {
        fmt.Println(m[1])
    }
    // PCRE/JS a(?=a) finds index 0 and 1 in "aaa". The capture-group
    // rewrite consumes the second "a", so the next search starts at 2.
    fmt.Println(regexp.MustCompile(`(a)a`).FindAllStringSubmatchIndex("aaa", -1))
    // Rewrite 2: find the candidate, then check the context in code.
    s := "foobar foobaz"
    for _, loc := range regexp.MustCompile(`foo`).FindAllStringIndex(s, -1) {
        if len(s) >= loc[1]+3 && s[loc[1]:loc[1]+3] == "bar" {
            fmt.Println("foo before bar at", loc[0])
        }
    }
}

// Output on Go 1.24:
// error parsing regexp: invalid named capture: `(?<=\$)\d+`
// 42
// 7
// [[0 2 0 1]]
// foo before bar at 0

Python: thousands separators with lookahead, fixed-width lookbehind, and the two width errors.

Python
import re

print(re.sub(r"\B(?=(?:\d{3})+(?!\d))", ",", "1234567"))
print(re.findall(r"(?<=\$)\d+", "cost $42, $7 and 9"))
print(re.search(r"(?<=ab|cd)x", "abx").group())
for p in (r"(?<=a+)b", r"(?<=a|bc)x"):
    try:
        re.compile(p)
    except re.error as e:
        print(p, "->", e)

# Output on Python 3.13:
# 1,234,567
# ['42', '7']
# x
# (?<=a+)b -> look-behind requires fixed-width pattern
# (?<=a|bc)x -> look-behind requires fixed-width pattern

JavaScript: the same separators, variable-length lookbehind, a password check and overlapping matches.

javascript
console.log("1234567".replace(/\B(?=(?:\d{3})+(?!\d))/g, ","));
console.log("cost $42, $7 and 9".match(/(?<=\$)\d+/g));
console.log(/(?<=a+)b/.test("aab"), /(?<=a|bc)x/.test("bcx"));
console.log(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}$/.test("Passw0rdX"));
console.log([..."aaaa".matchAll(/(?=(aa))/g)].map(m => [m.index, m[1]]));

// Output on Node 22:
// 1,234,567
// [ '42', '7' ]
// true true
// true
// [ [ 0, 'aa' ], [ 1, 'aa' ], [ 2, 'aa' ] ]

In practice

  • Go regexp — By design has no lookaround (RE2 style) so matching stays linear; every form is a compile error. Observed on Go 1.24.
  • Python re — Fixed-width lookbehind only; error text `look-behind requires fixed-width pattern`. Observed on 3.13.
  • V8 Irregexp — Variable-length lookbehind is supported (`/(?<=a+)b/.test("aab")` is `true`); lookbehind needs ES2018 and a current engine. Observed on Node 22.22; browser support is per MDN and not run here.
  • GNU grep -P — PCRE2 10.42: `printf 'foobar\n' | grep -oP 'foo(?=bar)'` prints `foo`, and `grep -boP 'a(?=a)'` on `aaa` prints offsets `0:a` and `1:a`.
  • ripgrep — Rejects lookaround in the default engine and offers `-P` / `--engine auto` for PCRE2. Observed on rg 14.1.0.

Trade-offs

Pros

  • Lookaheads express "contains X and Y" and "X not followed by Y" as one pattern without consuming text.
  • Lookbehind keeps the context out of the match, so replacement and extraction see only the interesting part.
  • Behaviour is identical in Python, JavaScript and PCRE2 for fixed-width cases, so those patterns port well.

Cons

  • Not available in Go, ripgrep's default engine or any RE2-style engine, which is exactly where untrusted patterns are usually run.
  • Lookbehind length rules differ three ways (fixed, per-branch fixed, unbounded).
  • Stacked `(?=.*...)` lookaheads rescan the rest of the input each time and make patterns hard to read.

`(?>...)` and `a*+` commit to what they matched and never give it back: Python 3.11+ and PCRE2 have them, Go and JavaScript do not, and a lookahead plus backreference emulates an atomic group in JavaScript.

The problem

Backtracking engines retry shorter alternatives when the rest of the pattern fails. That is how `(a+)+$` takes exponential time on `aaaa...c`. An atomic group or possessive quantifier commits to its first successful match and never reconsiders it, which both prevents that blow-up and changes what the pattern matches.

How it works

  • Atomic group `(?>X)`: once X has matched, the engine throws away X's backtracking points. `(?>a+)a` on `aaa` does not match (the group took all three `a`), while `a+a` does. `(?>a|ab)c` on `abc` fails, `(?:a|ab)c` matches. Observed on Python 3.13 and PCRE2 10.42.
  • Possessive quantifiers are the single-item shorthand: `a*+` is `(?>a*)`, and `a++`, `a?+`, `a{1,3}+` work alike. `"[^"]*+"` on `say "hi" now` matches `"hi"`, and on `say "hi now` fails without retrying shorter runs.
  • Availability, as observed: PCRE2 and Python 3.13 accept both. Python added them in 3.11 per the documentation; older versions are not available here to test. JavaScript has neither (`(?>a+)a` gives `Invalid group`, `a++a` gives `Nothing to repeat`), and Go rejects both (`invalid or unsupported Perl syntax: `(?>``, `invalid nested repetition operator: `++``).
  • JavaScript emulation: lookaheads are atomic, so `(?=(a+))\1` captures the greedy run and then consumes exactly that text. `(?=(a+))\1a` on `aaa` is `false` (like `(?>a+)a`) while `a+a` is `true`; `(?=(a|ab))\1c` on `abc` is `false` while `(?:a|ab)c` is `true`; `(?=(a+))\1b` on `aaab` is `true`. The price: the emulation uses up a capture number, so `(?=(a+))\1b(c)` reports `aa` as group 1 and `c` as group 2.
  • Effect on cost (trend only): `^(a+)+$` on `a` repeated n times plus `c` took about four times longer for every two extra characters on Python 3.13 and Node 22 (n = 18 to 24), i.e. exponential. `^(?>a+)+$` and `^(?:a++)+$` on Python grew roughly in proportion to n (1000 to 8000), and the JavaScript emulation `^(?:(?=(a+))\1)+$` did too.
  • PCRE2 turns runaway backtracking into an error instead of a hang: `grep -cP '^(a+)+$'` on 30, 34 and 40 `a` plus `c` printed `grep: <file>: exceeded PCRE's backtracking limit`, while `^(?>a+)+$` returned `0` at once. Go (RE2) never backtracks: `^(a+)+$` on 100k to 400k `a` plus `c` doubled in time as the input doubled.
  • Atomic is not a pure optimization, it changes semantics. Use it when the first successful match of the group is the only one you want (a delimited token, a quoted string, a number followed by a terminator), not as a blanket speed-up for alternations like `a|ab`.

Examples

Python 3.11+: atomic group and possessive quantifier refuse to give characters back.

Python
import re

print(re.search(r"(?>a+)a", "aaa"))
print(re.search(r"a++a", "aaa"))
print(re.search(r"(?>a|ab)c", "abc"), re.search(r"(?:a|ab)c", "abc").group())
print(re.search(r"(?>a+)b", "aaab").group())

# Output on Python 3.13:
# None
# None
# None abc
# aaab

JavaScript: no atomic syntax, so a lookahead plus backreference stands in; both native forms are errors.

javascript
// (?>a+) has no JS syntax; (?=(a+))\1 emulates it with a lookahead and a backreference.
const atomic = /(?=(a+))\1a/;
console.log(atomic.test("aaa"), /a+a/.test("aaa"));
console.log(/(?=(a|ab))\1c/.test("abc"), /(?:a|ab)c/.test("abc"));
for (const src of ["(?>a+)a", "a++a"]) {
  try {
    new RegExp(src);
  } catch (e) {
    console.log(e.message);
  }
}

// Output on Node 22:
// false true
// false true
// Invalid regular expression: /(?>a+)a/: Invalid group
// Invalid regular expression: /a++a/: Nothing to repeat

In practice

  • PCRE2 — Atomic groups, possessive quantifiers and a match limit (10,000,000 by default in the library build used here) that turns runaway patterns into `exceeded PCRE's backtracking limit`.
  • Python re — Atomic groups and possessive quantifiers are documented as new in 3.11; accepted on 3.13 (`a++a` never matches `aaa`).
  • V8 Irregexp — No atomic syntax; the lookahead-plus-backreference idiom is the workaround, at the cost of one capture number. Observed on Node 22.22.
  • Go regexp — No atomic groups or possessive quantifiers and no need for them to avoid blow-up, because the matcher is automaton-based; they cannot be used to express "commit" semantics either.

Trade-offs

Pros

  • Removes the retry paths behind catastrophic backtracking while keeping a normal backtracking engine.
  • Makes failure fast: a possessive `[^"]*+` never rescans shorter runs.
  • Documents intent: the token is final once read.

Cons

  • Only PCRE2 and Python 3.11+ among the four; JavaScript needs the capture-consuming emulation and Go has nothing.
  • Changes which strings match, so adding it to an existing pattern needs regression tests.
  • Does not repair an ambiguous pattern in an engine that lacks it; the fix there is to remove the ambiguity or switch to an RE2-style engine.

`(?(1)yes|no)`, `(?R)`, `(?1)`, `(?&name)`: PCRE2 has them all, Python only the group-test conditional, Go and JavaScript none; and why balanced brackets are a parser job.

The problem

Some formats need memory the regular-expression model does not have: an optional opening parenthesis that must be closed, or arbitrarily nested brackets. PCRE added conditional groups and recursive calls to cover them. Few engines followed, and even in PCRE they are the part of a pattern nobody can read six months later.

How it works

  • Conditional `(?(1)yes|no)`: if group 1 took part in the match use `yes`, otherwise `no` (optional). `^(\()?\d+(?(1)\))$` accepts `12` and `(12)` and rejects `(12` and `12)`, identically on Python 3.13 and PCRE2 10.42 (`grep -P` gave the same). Names: Python `(?(name)...)` with `(?P<name>...)`, PCRE2 `(?(<name>)...)` or `(?(name)...)`. A missing group is a compile error (Python `invalid group reference 2`, PCRE2 `reference to non-existent subpattern`).
  • Only PCRE2 accepts an assertion as the condition (`(?(?=a)ab|cd)` matches `ab`; Python reports `bad character in group name '?=a'`) or the recursion test `(?(R)a|b)`. Go and JavaScript reject every conditional (`invalid or unsupported Perl syntax: `(?(``, `Invalid group`).
  • Recursion and subroutine calls are PCRE2-only: `(?R)` re-enters the whole pattern, `(?1)` group 1, `(?&name)` or `(?P>name)` a named group. `^(\((?:[^()]++|(?1))*\))$` matches `(a(b)c)` and rejects `(a(b)`. Using `(?R)` inside an anchored pattern recurses into the anchors too: `^\((?:[^()]++|(?R))*\)$` did not match `(a(b)c)`. Python reports `unknown extension ?R at position 14`, JavaScript `Invalid group`, Go `invalid or unsupported Perl syntax: `(?R``.
  • Why a regex is the wrong tool: balanced brackets are not a regular language, so an automaton-based engine cannot recognise unbounded nesting at all, and a backtracking engine only manages it through the recursion extension. A pattern unrolled to a fixed depth is regular and works everywhere, but grows with each level: the depth-3 form `^\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\)$` matched `(a(b(c)))` and `(a(b)c(d))` and rejected `((((x))))` and `(a(b` in Go, Python, JavaScript and PCRE2 alike.
  • Limits: PCRE2 guards recursion with its match limit (10,000,000 in the library build used here) and refuses patterns that recurse at the same position without consuming (`(?R)?a` compiles but fails at match time with `nested recursion at the same subject position`). Deep or hostile input is better handled by a counter loop or a real parser, which also reports the position of the error.
  • The third-party Python `regex` package (2026.9.29, installed here) supports the PCRE-style forms that `re` lacks: `(?1)`, `(?&p)` and `(?R)` all matched `(a(b)c)`. It is not part of the standard library and not tabulated on this sheet.

Examples

Go
import (
    "fmt"
    "regexp"
)

// balanced unrolls nesting up to depth levels. The language of balanced
// parentheses is not regular, so every extra level needs another copy.
func balanced(depth int) *regexp.Regexp {
    inner := `\([^()]*\)`
    for i := 1; i < depth; i++ {
        inner = `\((?:[^()]|` + inner + `)*\)`
    }
    return regexp.MustCompile(`^` + inner + `$`)
}

func demo() {
    for _, p := range []string{`^(\()?\d+(?(1)\))$`, `\((?:[^()]|(?R))*\)`, `(\d+)-(?1)`} {
        _, err := regexp.Compile(p)
        fmt.Println(err)
    }
    re := balanced(3)
    for _, s := range []string{"(a(b(c)))", "(a(b)c(d))", "((((x))))", "(a(b"} {
        fmt.Println(s, re.MatchString(s))
    }
}

// Output on Go 1.24:
// error parsing regexp: invalid or unsupported Perl syntax: `(?(`
// error parsing regexp: invalid or unsupported Perl syntax: `(?R`
// error parsing regexp: invalid or unsupported Perl syntax: `(?1`
// (a(b(c))) true
// (a(b)c(d)) true
// ((((x)))) false
// (a(b false

Python: the group conditional works; assertion conditions and recursion are rejected.

Python
import re

pat = re.compile(r"^(\()?\d+(?(1)\))$")
for s in ("12", "(12)", "(12", "12)"):
    print(s, bool(pat.match(s)))
for p in (r"(?(?=a)ab|cd)", r"\((?:[^()]++|(?R))*\)"):
    try:
        re.compile(p)
    except re.error as e:
        print(e)

# Output on Python 3.13:
# 12 True
# (12) True
# (12 False
# 12) False
# bad character in group name '?=a' at position 3
# unknown extension ?R at position 14

In practice

  • PCRE2 — Full set: group and assertion conditions, `(?R)`, `(?1)`, `(?&name)`, `(?P>name)`. Observed on 10.42 via a C harness and `grep -P`.
  • Python re — Only `(?(id/name)yes|no)`; no recursion. Observed on 3.13.
  • Go regexp — Rejects conditionals and recursion at compile time; use a fixed-depth unrolled pattern or a hand-written scanner.
  • V8 Irregexp — No conditionals or recursion; the same fixed-depth unrolling works. Observed on Node 22.22.

Trade-offs

Pros

  • A group conditional encodes "optional prefix needs a matching suffix" without duplicating the pattern.
  • Recursive PCRE2 patterns are compact for a fixed grammar such as parentheses.
  • A fixed-depth unrolled pattern is plain regular syntax and runs in every engine, including Go.

Cons

  • Only PCRE2 supports the full set, so the patterns do not port to Go, JavaScript or Python `re`.
  • Hard to read and to debug; recursion can hit the match limit on hostile input.
  • A regex cannot report where the nesting went wrong, while a small parser can.

`\p{L}`, `\p{Han}`, `\X`: which engines support Unicode properties and how scripts are spelled, why JavaScript needs `u` or `v`, why Python `re` has none, and the case-folding and normalization traps.

The problem

`[a-zA-Z]` and `\w` stop at ASCII, and once the text contains `café`, `漢字` or an emoji, patterns that looked right drop or split characters. Unicode property escapes name a class (letters, digits, a script) instead of listing code points, but every engine supports a different subset and spells it differently, and case-insensitive matching and combining marks add traps of their own.

How it works

  • General categories: `\p{L}` letters, `\p{Lu}` uppercase, `\p{N}` numbers, `\p{Nd}` decimal digits, `\p{P}` punctuation, `\p{Zs}` space separators, negated with `\P{L}` or `[^\p{L}]`. They work in Go, in JavaScript with `u` or `v`, and in PCRE2; Python `re` has none (`bad escape \p at position 0`). JavaScript without `u` reads `\p{L}` as the literal text `p{L}`.
  • Spellings differ. `\pL` (no braces) works in Go and PCRE2, not in JavaScript (`Invalid property name`). Negation `\p{^L}` works in Go and PCRE2 only. Scripts: `\p{Han}`, `\p{Greek}`, `\p{Hiragana}` work in Go and PCRE2; JavaScript needs `\p{Script=Han}`, `\p{sc=Han}` or `\p{scx=Han}`; Go rejects `Script=Han` (`invalid character class range: `\p{Script=Han}``); PCRE2 accepts `Han`, `Script=Han` and `scx:Han`.
  • Binary and extra properties: `\p{Emoji}`, `\p{Alphabetic}`, `\p{Lowercase}`, `\p{ASCII}` work in JavaScript and PCRE2 but not in Go (`invalid character class range`). `\p{Any}` works in all three; `\p{LC}` in JavaScript and PCRE2; `\p{L&}` in PCRE2 only; long names such as `\p{Lowercase_Letter}` in JavaScript only (PCRE2: `unknown property after \P or \p`).
  • JavaScript `u` switches to code-point semantics and enables `\p{...}`; `v` adds set algebra (`[\p{L}--[a-z]]` on `abcXYZ` gives `XYZ`, `[\p{L}&&\p{ASCII}]`) and string properties like `\p{RGI_Emoji}`, and cannot be combined with `u`. Without `u`, `.` splits a surrogate pair (`"😀".length` is 2 and `/^.$/` fails), and `[😀-🙏]` is a `Range out of order` error.
  • Python `re` has no property escapes and leans on a Unicode-aware `\w`. Explicit ranges work everywhere (the range U+4E00 to U+9FFF, written literally as `[一-鿿]+`, on `a漢字` gave `漢字` in all four; PCRE2 in UTF mode), but cover only that block. The third-party `regex` package (2026.9.29, installed here) adds `\p{L}`, `\p{Han}` and `\X`: `regex.findall(r"\p{L}+", "café 中文")` gave `['café', '中文']`.
  • Grapheme clusters: `\X` matches one user-perceived character and exists in PCRE2 (and Python `regex`); Go says `invalid escape sequence: `\X``, JavaScript `Invalid escape`, Python `re` `bad escape \X`. Without it, `.` counts code points: `^..$` matches the two-character flag emoji and `^.{5}$` the family emoji joined by zero-width joiners.
  • Case folding. `i` uses Unicode simple folding, but only when the engine is in Unicode mode: `(?i)k` matches the Kelvin sign U+212A in Go and Python, in JavaScript only with `u`, in PCRE2 only in UTF mode. `ß` versus `SS` never matches in any engine (no full folding). Python's `i` also matches `İ` (U+0130) for `i`; Go, JavaScript and PCRE2 do not. `(?i)\p{Lu}` matches lowercase `a` in Go and in JavaScript `/iu`, but not in PCRE2 10.42.
  • Normalization: `é` is either one code point (NFC) or `e` plus U+0301 (NFD). `^.$` and `^\p{L}$` reject the decomposed form in every engine; `^\p{L}\p{M}*$` accepts both in Go, JavaScript and PCRE2. Normalize first (`"...".normalize("NFC")` in JavaScript, `unicodedata.normalize("NFC", s)` in Python; Go needs `golang.org/x/text/unicode/norm`, which was not run here).
  • Unicode data versions differ per engine, so newly added characters can match in one and not another. Observed: Go 1.24 reports Unicode 15.0.0, Python 3.13 15.1.0, Node 22.22 (ICU 77.1) 16.0, PCRE2 10.42 14.0.0.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    fmt.Printf("%q\n", regexp.MustCompile(`\p{Han}+`).FindAllString("go语言 and 漢字", -1))
    fmt.Printf("%q\n", regexp.MustCompile(`\pL+`).FindAllString("café Ünï", -1))
    fmt.Printf("%q\n", regexp.MustCompile(`\p{Lu}`).FindAllString("aBc", -1))
    fmt.Printf("%q\n", regexp.MustCompile(`(?i)\p{Lu}`).FindAllString("aBc", -1))
    fmt.Println(regexp.MustCompile(`^\p{L}$`).MatchString("e\xcc\x81"))
    fmt.Println(regexp.MustCompile(`^\p{L}\p{M}*$`).MatchString("e\xcc\x81"))
    for _, p := range []string{`\p{Script=Han}`, `\p{ASCII}`, `\p{Emoji}`, `\X`} {
        _, err := regexp.Compile(p)
        fmt.Println(err)
    }
}

// Output on Go 1.24:
// ["语言" "漢字"]
// ["café" "Ünï"]
// ["B"]
// ["a" "B" "c"]
// false
// true
// error parsing regexp: invalid character class range: `\p{Script=Han}`
// error parsing regexp: invalid character class range: `\p{ASCII}`
// error parsing regexp: invalid character class range: `\p{Emoji}`
// error parsing regexp: invalid escape sequence: `\X`

JavaScript: `Script=Han`, `v`-flag set subtraction, surrogate pairs with and without `u`, `\p{Lu}` under `iu`, and normalization.

javascript
const nfd = "e" + String.fromCodePoint(0x301);
console.log("go语言 and 漢字".match(/\p{Script=Han}+/gu));
console.log("abcXYZ".match(/[\p{L}--[a-z]]+/v)[0]);
console.log("😀".length, /^.$/.test("😀"), /^.$/u.test("😀"));
console.log(/\p{Lu}/iu.test("a"), /^\p{L}$/u.test(nfd), /^\p{L}\p{M}*$/u.test(nfd));
console.log(nfd.length, nfd.normalize("NFC").length);
for (const src of ["\\p{Han}", "\\pL"]) {
  try {
    new RegExp(src, "u");
  } catch (e) {
    console.log(e.message);
  }
}

// Output on Node 22:
// [ '语言', '漢字' ]
// XYZ
// 2 false true
// true false true
// 2 1
// Invalid regular expression: /\p{Han}/u: Invalid property name
// Invalid regular expression: /\pL/u: Invalid property name

Python: decomposed text defeats `.`, `unicodedata` normalizes it, `re.ASCII` limits case folding, and `\p` is an error.

Python
import re
import unicodedata

nfd = unicodedata.normalize("NFD", "é")
print(len("é"), len(nfd), re.fullmatch(r".", nfd) is None)
print(unicodedata.normalize("NFC", nfd) == "é")
kelvin = chr(0x212A)
print(re.search(r"(?i)k", kelvin) is not None, re.search(r"(?ai)k", kelvin) is not None)
try:
    re.compile(r"\p{L}")
except re.error as e:
    print(e)

# Output on Python 3.13:
# 1 2 True
# True
# True False
# bad escape \p at position 0

In practice

  • Go regexp — Property classes come from the `unicode` tables: general categories and scripts (`\p{Han}`) but no binary properties, no `Script=` form and no `\X`. Observed on Go 1.24 (Unicode 15.0.0).
  • V8 Irregexp — ES2018 property escapes under `u`, plus `v` set notation; scripts need `Script=` or `scx=`. Observed on Node 22.22 (Unicode 16.0 data).
  • PCRE2 — Properties, scripts, `\X`, `(*UTF)` and `(*UCP)`; the Unicode version is a build property (14.0.0 in 10.42). In `grep -P` on a UTF-8 locale `\d` stays ASCII while `\p{Nd}` matches U+0663.
  • Python re — No `\p`; `unicodedata.unidata_version` printed 15.1.0 on 3.13. Third-party `regex` fills the gap but is not part of the standard library.

Trade-offs

Pros

  • Property classes say what you mean (`\p{L}`, `\p{Han}`) and track new characters as the Unicode data is updated.
  • `\p{L}\p{M}*` handles both composed and decomposed text; `\X` handles grapheme clusters where available.
  • JavaScript `v` gives set operations that no other engine here offers.

Cons

  • No syntax works in all four engines: property names, scripts and negation are spelled differently, and Python `re` has none.
  • Behaviour depends on mode flags (`u`, `v`, UTF, UCP) that are easy to forget, and results depend on each engine's Unicode version.
  • Case-insensitive matching is only simple folding, so `ß` and `SS` never match and `(?i)\p{Lu}` differs between engines.

`$1`, `\1`, `\g<1>`, `${name}`, `$&`, `$$`: how each engine writes group references and literal dollars in a replacement string, what happens with unknown groups, and where Go's `Expand` and `ReplaceAllLiteralString` fit.

The problem

A replacement string is a tiny template language, and it is not the regex language. Go and JavaScript use `$1`, Python and sed use `\1`, JavaScript has `$&` where Python has `\g<0>`, an unknown group is empty in one engine, literal text in another and an error in a third, and `$` must be doubled in some. Pasting `s/(\w+) (\w+)/\2 \1/` into Go leaves `\2 \1` in the output.

How it works

  • Numbered groups: Go `$1` or `${1}`; Python `\1` or `\g<1>`; JavaScript `$1`; PCRE2 `pcre2_substitute` `$1` or `${1}`; sed `\1`. `(\w+) (\w+)` on `ab cd` becomes `cd ab` with each engine's own syntax. Crossing syntaxes is silent: Python with `$2 $1` outputs `$2 $1`, and Go, JavaScript and PCRE2 with `\2 \1` output `\2 \1`.
  • Digits after a reference. Go reads `$1x` as the group named `1x` and substitutes nothing (`(a)` replaced with `$1x` gives an empty string); write `${1}x` (`ax`). `$10` is group 10 (empty). Python's `\10` is an error (`invalid group reference 10`); write `\g<1>0` (`a0`). JavaScript's `$10` with one group gives `a0` (it falls back to `$1` plus `0`), and `${1}` is not JavaScript syntax (it stays literal). PCRE2 `$10` is an error (`unknown substring`); sed `\10` is group 1 plus `0`.
  • Whole match: Go `$0` or `${0}`; Python `\g<0>` (and `\0` is a NUL character, not the match); JavaScript `$&` (`$0` is literal text); PCRE2 `$0` or `${0}`; sed `&`, with `\&` for a literal ampersand. JavaScript alone also has `` $` `` (text before) and `$'` (text after): `"abc".replace(/b/, "[$`|$&|$']")` gives `a[a|b|c]c`.
  • Named groups: Go `${name}` or `$name` (`$x1` means the group `x1`, so use `${x}1`); Python `\g<name>`; JavaScript `$<name>`, which only works when the regex has named groups (otherwise `$<b>` stays literal); PCRE2 `${name}` or `$name`; sed has none. `$<name>` is not Go syntax (kept literally) and gives `invalid replacement string` in PCRE2.
  • Literal `$` and backslash. Go, JavaScript and PCRE2 write `$$`; Python treats `$` as an ordinary character; sed too. A lone trailing `$` stays a literal `$` in Go and JavaScript but is `invalid replacement string` in PCRE2. Python processes backslash escapes in the template (`\n` becomes a newline, `\\` one backslash, unknown ASCII-letter escapes such as `\q` or `\d` fail with `bad escape`); Go and JavaScript keep a backslash as two plain characters. PCRE2 does so too unless the extended option is set, which processes `\n`, `\\`, `\x41` and case escapes.
  • Unknown or unset groups. A group number that does not exist: Go gives an empty string (`$2` with one group), JavaScript keeps `$2` literally, Python raises `invalid group reference 2`, PCRE2 `unknown substring`, sed refuses to compile (`invalid reference \2 on `s' command's RHS`). A group that exists but did not take part: Go, Python and JavaScript give an empty string; PCRE2 fails with `requested value is not set` unless the unset-empty option is on; sed gives empty.
  • Treating the replacement as plain text: Go `ReplaceAllLiteralString` (`$2 $1` stays `$2 $1`), PCRE2's literal substitute option, or a callback. Callbacks: Go `ReplaceAllStringFunc` sees only the matched text (for groups use `FindStringSubmatchIndex` with `ExpandString`), Python accepts a callable taking the match object, JavaScript a function `(match, p1, ..., offset, string, groups)`. Case conversion needs a callback in Go, Python and JavaScript; PCRE2's extended mode does it in the template (global `\U$1\E` with `(\w+)` turns `ab cd` into `AB CD`, global `\u$1\L$2` with `(\w)(\w+)` into `Ab Cd`), and GNU sed has `\U\1`.
  • How many replacements: Go `ReplaceAll*` replaces every match; Python `re.sub` every match (`count=` limits it); JavaScript `replace` replaces the first match unless the regex has `g` (`"aaa".replace(/a/, "-")` is `-aa`) and `replaceAll` throws for a non-global regex; PCRE2 needs the global option; sed `s///` replaces the first, `s///g` all.
  • Empty matches: replacing `a*` with `-` in `baac` gives `-b-c-` in Go and GNU sed but `-b--c-` in Python 3.13, JavaScript and PCRE2 (global): Go does not allow an empty match directly after a non-empty one, the others do. `x*` in `abc` gives `-a-b-c-` everywhere.

Examples

Go
import (
    "fmt"
    "regexp"
)

func demo() {
    re := regexp.MustCompile(`(?P<first>\w+) (?P<second>\w+)`)
    const in = "ab cd"
    fmt.Println(re.ReplaceAllString(in, "$2 $1"))
    fmt.Println(re.ReplaceAllString(in, "${second}-${first}"))
    fmt.Println(re.ReplaceAllString(in, "$1x|${1}x|$$|$0"))
    fmt.Println(re.ReplaceAllString(in, `\2 $&`))
    fmt.Println(re.ReplaceAllLiteralString(in, "$2 $1"))
    fmt.Println(re.ReplaceAllStringFunc(in, func(m string) string { return "<" + m + ">" }))
    // Expand appends to dst; template is the same $ syntax.
    m := re.FindStringSubmatchIndex(in)
    fmt.Println(string(re.ExpandString(nil, "${second}/${first}", in, m)))
    fmt.Println(regexp.MustCompile(`a*`).ReplaceAllString("baac", "-"))
}

// Output on Go 1.24:
// cd ab
// cd-ab
// |abx|$|ab cd
// \2 $&
// $2 $1
// <ab cd>
// cd/ab
// -b-c-

Python: `\1`, `\g<name>`, literal `$`, `\g<1>0`, empty matches, a callable, and the `\10` error.

Python
import re

print(re.sub(r"(\w+) (\w+)", r"\2 \1", "ab cd"))
print(re.sub(r"(?P<a>\w+) (?P<b>\w+)", r"\g<b> \g<a>", "ab cd"))
print(re.sub(r"(\d+)", r"$\1", "5"))
print(re.sub(r"(\d+)", r"\g<1>0", "5"))
print(re.sub(r"a*", "-", "baac"))
print(re.sub(r"(\w+)", lambda m: m.group(1).upper(), "ab cd"))
try:
    re.sub(r"(a)", r"\10", "a")
except re.error as e:
    print(e)

# Output on Python 3.13:
# cd ab
# cd ab
# $5
# 50
# -b--c-
# AB CD
# invalid group reference 10 at position 1

JavaScript: `$1`, `$<name>`, `$$`, `$&`, the prefix and suffix forms, missing groups kept literally, and a function replacer.

javascript
console.log("ab cd".replace(/(\w+) (\w+)/, "$2 $1"));
console.log("ab cd".replace(/(?<a>\w+) (?<b>\w+)/, "$<b> $<a>"));
console.log("5".replace(/(\d+)/, "$$$1"), "abc".replace(/b/, "[$`|$&|$']"));
console.log("a".replace(/(a)/, "$10"), "a".replace(/(a)/, "$2"), "a".replace(/(a)/, "${1}"));
console.log("baac".replace(/a*/g, "-"));
console.log("ab cd".replace(/\w+/g, m => m.toUpperCase()));

// Output on Node 22:
// cd ab
// cd ab
// $5 a[a|b|c]c
// a0 $2 ${1}
// -b--c-
// AB CD

In practice

  • Go regexp — `ReplaceAllString` / `Expand` use `$name` and `${name}`; `ReplaceAllLiteralString` copies the replacement verbatim; `ReplaceAllStringFunc` gets only the match. Observed on Go 1.24.
  • Python re — `re.sub` templates use `\1` and `\g<name>`, process backslash escapes, and raise on unknown groups; a callable avoids the template entirely. Observed on 3.13.
  • V8 Irregexp — `String.prototype.replace` patterns: `$1`, `$<name>`, `$&`, `` $` ``, `$'`, `$$`; `replaceAll` requires a global regex. Observed on Node 22.22.
  • PCRE2 — `pcre2_substitute` has its own `$n`, `${n}`, `$name`, `$$` syntax, and options for global, extended (`\U...\E`, `${1:+yes:no}`), literal and unset-empty. Observed through a C harness on 10.42; `grep -P` has no replacement, and host languages such as PHP or Perl define their own templates (not covered).
  • GNU sed — ERE replacement uses `\1`...`\9`, `&` for the whole match, `\U`/`\L`/`\u` case conversion; `\10` means group 1 plus `0`; an out-of-range group is a compile error. Observed on GNU sed; BSD sed is per its manual and not run here.

Trade-offs

Pros

  • Template replacement is the shortest way to reorder or wrap captured text.
  • Callbacks (and Go's literal variant) sidestep template syntax entirely and are safe for user-supplied text.
  • Braced forms (`${1}`, `\g<1>`) make digit-after-reference cases unambiguous.

Cons

  • Four or five different template dialects; a pattern pasted between languages fails silently.
  • Unknown groups are empty, literal or an error depending on the engine.
  • A user-controlled replacement string can inject group references or escapes unless a literal or callback form is used.

Engines & differences

Why PCRE, Python re and V8 can blow up exponentially while RE2 and Go regexp stay linear, what that costs in features, and when leftmost-first vs leftmost-longest matters.

The problem

The same pattern text can finish instantly in one language and hang a server in another. Engines fall into two families: backtracking matchers (Perl, PCRE2, Python `re`, V8 Irregexp) try alternatives one at a time and undo work on failure, and automaton matchers (RE2, Go `regexp`, Rust `regex`, GNU grep `-E`) track all live states at once. The first family has more syntax and an exponential worst case; the second has a linear guarantee and rejects the syntax that cannot be done that way. Knowing which family you are on explains most compile errors and most performance surprises.

How it works

  • A backtracking engine walks the pattern against the input, remembers choice points, and on failure returns to the last one. Nested or overlapping quantifiers multiply the choice points: `^(a+)+$` against `aaa…b` roughly quadrupled its time for every two extra characters on Python 3.13 and Node 22.
  • An automaton engine compiles the pattern to a state machine (an NFA simulated in lockstep, optionally cached as a DFA) and consumes each input character once, so run time is proportional to input length times pattern size. The same pattern on Go roughly doubled its time when the input doubled, and `grep -E` stayed flat up to 160000 characters.
  • Features that need memory of earlier matches or unbounded lookahead break the one-pass model, so RE2-style engines omit them: backreferences, lookaround, atomic groups, possessive quantifiers, conditionals and recursion. Go reports them at compile time (`invalid or unsupported Perl syntax: `(?=``, `invalid escape sequence: `\1``), so the failure is loud rather than a silent mismatch.
  • Backtracking engines add the features, then bolt on safety valves: `grep -P` stopped with `exceeded PCRE's backtracking limit` from 23 characters (22 answered) on `^(a+)+$` (PCRE2 10.42), instead of hanging. No such limit was observed on Python `re` or V8 in the versions tested; the input length or a timeout is the only guard.
  • Choice among alternatives differs by design. Perl-family engines are leftmost-first: `a|ab` on `ab` returns `a`. POSIX specifies leftmost-longest, and GNU `grep -E` and `sed -E` returned `ab`. Go uses leftmost-first by default even though it is automaton-based; `Regexp.Longest()` switches one compiled pattern to leftmost-longest.
  • Automaton engines still pay for pattern size, not input size: Go caps repeat counts at 1000 (nested products too: `(a{500}){500}` is rejected), so an untrusted pattern can be refused at compile time even where untrusted input is safe.
  • ripgrep 14.1.0 uses Rust's `regex` by default and says so: `look-around, including look-ahead and look-behind, is not supported` and `backreferences are not supported`, with `-P` as the PCRE2 opt-in. This page does not cover Rust beyond that observation.

Examples

Go
import (
    "fmt"
    "regexp"
)

// firstVsLongest: RE2 syntax, Perl-style choice of alternative by default.
func firstVsLongest() {
    re := regexp.MustCompile("a|ab")
    fmt.Printf("%q\n", re.FindString("ab"))
    re.Longest()
    fmt.Printf("%q\n", re.FindString("ab"))
}

// rejected: the price of the linear-time guarantee is a compile error.
func rejected() {
    for _, p := range []string{"foo(?=bar)", "(?<=a)b", "(?>a+)b", "a*+"} {
        _, err := regexp.Compile(p)
        fmt.Println(err)
    }
}

The same pattern on two GNU grep engines, and POSIX alternation on sed -E (observed output in the comments).

bash
# GNU grep 3.11 / PCRE2 10.42, C.utf8 locale
s=$(printf 'a%.0s' {1..24})
printf '%sb\n' "$s" | grep -cP '^(a+)+$'   # grep: (standard input): exceeded PCRE's backtracking limit
printf '%sb\n' "$s" | grep -cE '^(a+)+$'   # 0, no backtracking
printf 'ab\n' | sed -E 's/a|ab/Z/'          # Z: POSIX leftmost-longest

In practice

  • RE2 — Documents a linear-time guarantee in input size and deliberately omits backreferences and lookaround (per the RE2 documentation; not run here).
  • Go regexp — Implements the RE2 syntax with leftmost-first matching by default and `Longest()` for POSIX semantics. Unsupported syntax fails in `Compile`, so a bad pattern shows up at start-up when compiled at package level.
  • V8 Irregexp — A backtracking engine behind JavaScript `RegExp`; supports variable-width lookbehind and named groups, and a catastrophic pattern blocks the event loop thread (exponential trend observed on Node 22).
  • PCRE2 — Backtracking library behind `grep -P` and many servers; the most feature-complete column of the matrix, with match and backtracking limits as the guard rail.
  • GNU grep — `-E` stayed flat on the ReDoS sample, `-P` hands the pattern to PCRE2 and hit its backtracking limit; one binary, two behaviours.

Trade-offs

Pros

  • Automaton engines give a run-time bound that does not depend on how adversarial the input is
  • Backtracking engines cover lookaround, backreferences, atomic groups and recursion in one syntax
  • Knowing the family predicts which constructs fail at compile time and which fail in production

Cons

  • Automaton engines reject whole feature groups, so patterns copied from PCRE or JavaScript often do not compile
  • Backtracking engines need input limits, timeouts or rewrites to be safe on untrusted input
  • Leftmost-first and leftmost-longest can return different matches for the same alternation

The constructs that behaved identically on Go RE2, Python re, JavaScript, PCRE2 and GNU ERE in a 61-case corpus, and the ones that silently differ; use it for regexes shared across languages.

The problem

Some regexes are written once and run in many places: a pattern in a config file read by Go and Python services, a gateway or WAF rule, a log pipeline filter, a validation rule shared by a browser and a backend. Each engine accepts a slightly different language, and the differences are not all errors: several constructs compile everywhere and match differently. The safe approach is to restrict shared patterns to a subset that was run on every target.

How it works

  • Method: 61 pattern and input pairs were run on Go 1.24.7, Python 3.13.16, Node v22.22.0, `grep -P` (PCRE2 10.42) and `grep -E` (GNU grep 3.11), comparing the first match. 48 gave the same result on all five; the other 13 are the lists below.
  • Identical everywhere: literals; `.` on single-line text; `[abc]`, `[^abc]` and ranges such as `[a-z0-9_]`; `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`; `|`; capturing `( )`; `^` and `$` on one line; a backslash before any of `. * + ? ( ) [ ] { } | ^ $ \`; and `[.]`, `[*]`, `[+]`, `[(]`, `[$]`, `[|]` for a literal metacharacter.
  • Same on ASCII input only: `\w`, `\s`, `\b`. In ERE they are GNU extensions (not POSIX), and `\w` there depends on the locale; Python matches Unicode letters and digits for `\w` and `\d` where Go, JavaScript and PCRE2 do not. Use them only when the data is ASCII, otherwise spell the class out.
  • Compile errors on some target: `\d` (GNU ERE matched the letter `d`, no error), `(?:…)`, lookaround, `\t` (ERE read it as `t`), `{` at the start of a pattern (`{2}` is an error in Go, Python, JS and PCRE2, a literal in ERE), and `[[:digit:]]` (Python and JavaScript read it as a set of characters, so `a5b` did not match `a[[:digit:]]b`).
  • Silent differences: `a+?` is lazy everywhere except ERE, where it means `(a+)?` and matched `aaa`; `a{,2}` means `{0,2}` in Python and ERE and was literal text in Go, JavaScript and PCRE2 10.42 (PCRE2 10.43 and later read it as `{0,2}`, per its ChangeLog); `a|ab` returns `a` in four engines and `ab` in ERE; `^.$` did not match one emoji in JavaScript without the `u` flag.
  • Bracket expressions: `[]x]` is a class containing `]` in Go, Python, PCRE2 and ERE but an empty class followed by `x]` in JavaScript; `[\]]` fails in ERE (backslash is literal in POSIX brackets); `[\.]` matched a backslash in ERE only; `[\d]` and `\t` do not work in ERE. Keep classes to plain characters and ranges, put `-` last and `^` not first.
  • Rewrites that stay portable: `\d` becomes `[0-9]`; `(?:x)` becomes `(x)` when capture numbers do not matter; a lazy `.*?` becomes a negated class such as `[^"]*`; an alternation where one branch is a prefix of another is made unambiguous by anchoring (`^(a|ab)$` agreed on all five engines).
  • Flags are not part of the subset: case-insensitivity is `(?i)`, `re.I`, the `i` flag or `grep -i` depending on the host. Keep the pattern text flag-free and let the host supply the flag, or document which flags the shared rule assumes.

Examples

A small lint for shared patterns; output observed: True, False, False, False, True for the five samples. It is a denylist of the differences found above, not a proof of portability.

Python
import re

# Rejects constructs that failed or changed meaning on at least one of
# Go RE2, Python re, JavaScript, PCRE2 and GNU ERE in the 61-case corpus.
NOT_PORTABLE = re.compile(
    r"""\(\?                # any (? group: lookaround, (?:, flags, names
      | \\[dDAzZQEKXpPkg1-9]  # shorthands and escapes missing somewhere
      | \[\[:                 # POSIX classes (Python and JS read them as sets)
      | [*+?}]\?              # lazy quantifier (greedy in ERE)
      | [*+]\+                # possessive quantifier
      | \{,                   # {,n} is {0,n} only in Python and ERE
      | \[\^?[\]\\]           # ] first or backslash first in a class
    """,
    re.VERBOSE,
)


def portable(pattern: str) -> bool:
    return NOT_PORTABLE.search(pattern) is None


for p in [r"^[a-z0-9_]+@[a-z]+\.com$", r"(?:ab)+", r"\d{3}", r"a{,2}", r"[0-9]{1,3}"]:
    print(portable(p), p)

In practice

  • ModSecurity — Rule files carry PCRE-family patterns that other tools reuse, so a rule using lookbehind or `(?i)` will not compile if copied into a Go or POSIX consumer; checked against the portable list, not run here.
  • Cloudflare WAF — Documents its rules language as Rust-regex based, so lookaround and backreferences are unavailable there; per the vendor docs, not run here.
  • Go regexp — The strictest compile-time gate in the matrix; a pattern that compiles under `regexp.MustCompile` in a test is already free of the PCRE-only constructs.
  • GNU grep — `grep -E` is the lowest common denominator for shell tooling, but its `\d` is the letter `d` and `a+?` is greedy, so a pattern that works under `-P` needs a separate check.

Trade-offs

Pros

  • One pattern text, one test corpus, same result on every target
  • Failures move to review time instead of production time
  • Staying inside the subset also keeps the pattern linear-time on automaton engines

Cons

  • No lookaround, no lazy quantifiers, no `\d`: patterns get longer and less readable
  • The subset was checked on five engines and one version each; other engines, such as Java, .NET, PHP and Ruby, are not covered
  • Some jobs, such as bounded context checks, cannot be expressed at all and need code next to the regex

re.match vs search vs fullmatch, $ matching before a trailing newline, re.sub positional count, re.VERBOSE, and JavaScript g/y flags with lastIndex, replaceAll, named groups and \d.

The problem

Python and JavaScript share most syntax but differ in the API around it, and that API is where regex bugs hide: `re.match` that only looks at the start, a `$` that tolerates a trailing newline, a fourth positional argument that is a count rather than flags, a global JavaScript regex that remembers where it stopped, and `replaceAll` that insists on `g`. Each of these produced a wrong result or an exception on Python 3.13 or Node 22.

How it works

  • `re.match` anchors at the start only: `re.match(r"\d+", "id 42 ok")` is `None`, `re.search` finds `42`. `re.fullmatch` requires the whole string. Use `fullmatch` for validation instead of wrapping the pattern in `^…$`.
  • `$` in Python also matches just before a final newline: `re.search(r"^\d+$", "12\n")` matched `12`, while `re.fullmatch(r"\d+", "12\n")` and `\Z` did not. JavaScript (`/^\d+$/.test("12\n")` is `false`) and Go do not tolerate it.
  • `re.sub(pattern, repl, string, count=0, flags=0)`: the fourth positional argument is `count`. `re.sub("a", "X", "aAa", re.I)` passed `re.I` (value 2) as the count, returned `XAX`, and emitted `DeprecationWarning: 'count' is passed as positional argument`. Write `flags=re.I`.
  • `re.VERBOSE` ignores unescaped whitespace and `#` comments outside a character class. A literal space needs `[ ]` or `\ `, and a literal `#` needs `\#` or a class. `(?x)` must be at the start of the pattern in Python 3.11+; elsewhere it fails with `global flags not at the start of the expression`.
  • Python replacement strings use `\1`, `\g<1>` and `\g<name>`; an unknown group in the replacement raises `invalid group reference 1`. JavaScript uses `$1`, `$<name>`, `$&`, and `$$` for a literal dollar; a group that does not exist stays literal: `"x".replace(/x/, "$1")` returned `$1`.
  • A JavaScript regex with `g` or `y` is stateful. `re.test("a")` returned `true` with `lastIndex` 1, then `false` with `lastIndex` 0, then `true` again on the same input. Create the regex per call, or avoid `g` when you only want a boolean.
  • `String.prototype.replaceAll` and `matchAll` throw `TypeError` on a regex without `g` (`String.prototype.replaceAll called with a non-global RegExp argument`). `replace` with `g` replaces all; with a string pattern it replaces only the first.
  • JavaScript named groups use `(?<name>…)` and `\k<name>`, never `(?P<name>…)` (`Invalid group`); Python accepts only `(?P<name>…)` and `(?P=name)` (`(?<name>…)` gives `unknown extension ?<n`). Duplicate names are an error in both, even across `|` branches on Node 22.
  • Unicode defaults differ: Python `str` patterns make `\d` match `٣` and `\w` match `é` (`re.A` restricts to ASCII); JavaScript `\d` and `\w` stay ASCII, even with `u`. Without `u`, `.` treats an emoji as two UTF-16 units, so `/^.$/.test("😀")` is `false`. Node 22 has no `RegExp.escape`; escape with `s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")`.

Examples

Python 3.13 output in order: None, 42, 42, 12, None, XAX (with a DeprecationWarning), XXX.

Python
import re

s = "id 42 ok"
print(re.match(r"\d+", s))
print(re.search(r"\d+", s).group())
print(re.fullmatch(r"\d+", "42").group())
print(re.search(r"^\d+$", "12\n").group())
print(re.fullmatch(r"\d+", "12\n"))
print(re.sub("a", "X", "aAa", re.I))
print(re.sub("a", "X", "aAa", flags=re.I))

Node 22 output in order: true 1, false 0, true 1, the replaceAll TypeError message, XXX, 10/2026.

javascript
const re = /a/g;
console.log(re.test("a"), re.lastIndex);
console.log(re.test("a"), re.lastIndex);
console.log(re.test("a"), re.lastIndex);

try {
    "aaa".replaceAll(/a/, "X");
} catch (err) {
    console.log(err.message);
}
console.log("aaa".replaceAll(/a/g, "X"));
console.log("2026-10".replace(/(?<y>\d+)-(?<m>\d+)/, "$<m>/$<y>"));

In practice

  • Python re — The 3.13 standard-library module; `fullmatch`, `flags=` keyword use and a `$`-versus-`\Z` decision are the three habits that remove most validation bugs.
  • V8 Irregexp — Shared by Node and Chromium; stateful `g`/`y` regexes held in module scope are a classic source of alternating `true`/`false` results across requests.
  • ESLint — Ships rules around regex literals (for example `no-control-regex`, `prefer-named-capture-group`); the stateful-`g` pitfall is usually caught in review or tests instead.
  • Django — Its URL patterns and validators are Python `re` patterns, so the `$` newline tolerance and `\d` Unicode matching apply to them; behaviour noted from the `re` documentation, not run against Django here.

Trade-offs

Pros

  • Each pitfall has a one-line fix: `fullmatch`, `flags=`, a fresh regex object, or an explicit `g`
  • Python `fullmatch` and JavaScript sticky `y` express intent better than hand-written anchors
  • Python's Unicode-aware `\d`/`\w` handle non-ASCII text with no extra syntax

Cons

  • The same pattern text needs a different API call in each language to mean the same thing
  • Python's Unicode `\d` can accept digits that downstream code cannot parse as integers
  • JavaScript's stateful `g` regex makes shared module-level constants unsafe

BRE vs ERE escaping, grep -E vs -P, GNU extensions (\w, \<, backreferences in ERE), leftmost-longest, and what changes on macOS, Alpine and mawk.

The problem

The command line has its own regex dialects, and they are not the ones your language uses. `grep` defaults to BRE, `grep -E` and `sed -E` use ERE, `grep -P` uses PCRE2, and awk has its own flavour; the same characters need escaping in one dialect and mean something else in another. Scripts that work in a Linux shell then fail on macOS or Alpine because the tool is a different implementation.

How it works

  • BRE (the default for `grep` and `sed`): `+ ? | ( ) { }` are literal. `printf 'a+b\n' | grep -o 'a+b'` printed `a+b` and `grep -o 'a\+b'` matched `aab`. GNU adds the escaped forms `\+ \? \|` as extensions, and `\( \) \{ \}` are the standard grouping and interval forms.
  • ERE (`grep -E`, `sed -E`): `+ ? | ( ) { }` are operators and a backslash makes them literal (`a\+b` matched `a+b`). `sed -E` and `grep -E` also accept backreferences (`(ab)\1` matched `abab`), which is a GNU extension to POSIX ERE.
  • `\d` is not part of BRE or ERE. In GNU `grep -E` it matched the letter `d`; in `sed -E 's/\d+/N/'` it did nothing to `ab12`. Use `[0-9]` or `[[:digit:]]`. GNU also supports `\w`, `\s`, `\b`, `\<` and `\>`; `\w` depends on the locale (`é` matched under `C.utf8`, not under `C`).
  • ERE has no `(?:…)`, lookaround or lazy quantifiers, but no error either in grep: `?` right after `(` is dropped with `grep: warning: ? at start of expression`, so `(?:a)b` matched `:ab`. `sed -E` is stricter and reports `Invalid preceding regular expression`. `a+?` is `(a+)?` and stays greedy.
  • POSIX matching is leftmost-longest: `echo ab | sed -E 's/a|ab/Z/'` printed `Z`, replacing both characters. Perl-family tools (and `grep -P`) are leftmost-first and would stop at `a`.
  • `grep -P` is PCRE2 (GNU grep 3.11 reported PCRE2 10.42) and brings lookbehind, `\K`, lazy quantifiers and `\Q…\E`: `grep -oP '(?<=foo )bar'` printed `bar`. It cannot be combined with `-E` (`grep: conflicting matchers specified`), is line-oriented unless `-z` is used, and reports `exceeded PCRE's backtracking limit` on catastrophic input.
  • awk: the version here is mawk 1.3.4 (20240123). It supported `{2}` intervals, `[[:digit:]]`, and not `\d`, `\s`, `\w`, `\<`, `\b`; gawk was not installed, so its extensions (such as `\<`, `\>`, `\s`, `\w`, and `gensub`) are per its manual, not run here.
  • Not run here, per documentation only: macOS ships BSD-derived `grep` and `sed`, where `grep -P` is not available and `sed -i` needs an argument (`sed -i ''`); Alpine's `grep`, `sed` and `awk` are BusyBox applets whose option sets are build-dependent. Check `man grep` or `grep --help` on the target, or install GNU grep, instead of assuming.

Examples

BRE, ERE and PCRE2 side by side; the comments are the observed output.

bash
# GNU grep 3.11 / sed 4.9, C.utf8 locale (observed output after each #)
printf 'aab\n' | grep -oE 'a+b'                 # aab
printf 'a+b\n' | grep -o 'a+b'                 # a+b   (BRE: + is literal)
printf 'aab\n' | grep -o 'a\+b'                # aab   (GNU extension)
printf 'foo bar\n' | grep -oP '(?<=foo )bar'   # bar   (PCRE2 only)
printf 'ab12\n' | sed -E 's/[0-9]+/N/'         # abN
printf 'ab\n' | sed -E 's/a|ab/Z/'             # Z     (leftmost-longest)

In practice

  • GNU grep — `-G` (BRE, default), `-E`, `-F` (fixed string) and `-P` (PCRE2) in one binary; `-o` prints only the matched part, which makes it the quickest way to test a pattern's actual span.
  • GNU sed — BRE by default and ERE with `-E`; leftmost-longest matching and `\U`, `\L` case conversion in the replacement are GNU features.
  • mawk — The default `awk` on Debian-family systems like this one; tested intervals and POSIX classes work, `\d` and `\s` do not.
  • BusyBox — Provides `grep`, `sed` and `awk` on Alpine and many container images; option support depends on build configuration, so confirm with `--help` in the image (docs-only, not run here).
  • ripgrep — Rust `regex` by default, PCRE2 with `-P`/`--pcre2`; observed to reject lookaround and backreferences without it.

Trade-offs

Pros

  • ERE with `[0-9]` and `[[:alpha:]]` is understood by every grep and sed variant
  • `grep -oP` gives scripts lookbehind and `\K` without leaving the shell
  • POSIX leftmost-longest is predictable for log-slicing one-liners

Cons

  • BRE and ERE disagree on which characters need a backslash, so copied one-liners break silently
  • `grep -P` is missing or optional on some platforms and is not the same engine as ERE
  • GNU extensions (`\w`, `\<`, `\+`, ERE backreferences) are not portable to BSD or BusyBox without checking

Go regexp

Lookaround, backreferences, atomic groups, possessive quantifiers, conditionals and recursion fail at regexp.Compile in Go: the exact error text and what to write instead.

The problem

Patterns copied from PCRE docs, Python, JavaScript or Stack Overflow often fail in Go at startup with `error parsing regexp: invalid or unsupported Perl syntax`. Go's regexp package implements RE2 syntax: it gives up the features that need backtracking (lookaround, backreferences, atomic groups, possessive quantifiers, conditionals, recursion) in exchange for matching time that grows linearly with the input. Unsupported syntax is rejected when the pattern is compiled, never silently reinterpreted, but the message is often not the name of the feature: lookbehind reports `invalid named capture` and a backreference reports `invalid escape sequence`.

How it works

  • Errors come from `regexp.Compile` as a `*syntax.Error` with a `Code` and the offending `Expr`; the text is `error parsing regexp: <code>: `<fragment>``. `MustCompile` panics with `regexp: Compile(`(?<=a)b`): error parsing regexp: invalid named capture: `(?<=a)b``. The table `unsupported-in-go` lists the text observed on Go 1.24.7 for every construct below.
  • Lookahead `(?=` and `(?!` report `invalid or unsupported Perl syntax` with the fragment `(?=` or `(?!`. Lookbehind `(?<=` and `(?<!` report `invalid named capture`, and the quoted fragment runs from `(?<` to the end of the pattern (`x(?<=a)b(c)` quotes `(?<=a)b(c)`), because `(?<` is parsed as the start of a named group.
  • Atomic groups `(?>`, conditionals `(?(`, recursion `(?R` / `(?1` / `(?&`, `(?P=name)` / `(?P>name)`, extended mode `(?x`, comments `(?#`, branch reset `(?|` and quoted names `(?'` all land in the same `invalid or unsupported Perl syntax` family, quoting only the first characters. Only the flags `i`, `m`, `s` and `U` exist.
  • Possessive quantifiers are stacked quantifiers to the parser: `a*+`, `a++`, `a?+`, `a{2}+` and `a**` all report `invalid nested repetition operator` with the pair (`*+`, `++`, `?+`, `{2}+`, `**`). Only the lazy form `a*?` is allowed.
  • Backreferences are escapes the parser does not know: `\1` reports `invalid escape sequence: `\1``, `\g1` reports `\g`, `\k<x>` reports `\k`. So do `\Z`, `\G`, `\K`, `\X`, `\R`, `\h`, `\N`, `\C`, `\e`, `\cA`, `\u0041`, `\8` and `\b` inside a class. Valid escapes include `\A \z \b \B \d \s \w \pL \p{Han} \Q…\E \a \f \t \n \r \v \x41 \x{10FFFF}` and octal `\123`.
  • Limits are errors too. Counted repetition above 1000 is `invalid repeat count: `{1001}``, and nested counts multiply: `(?:a{500}){3}` fails on `{3}` while `(?:a{10}){10}` compiles. Size and depth are capped as well: 5000 copies of `\pL{1000}` gave `expression too large` (1000 copies compiled) and 1000 nested groups gave `expression nests too deeply`.
  • Silent differences are the dangerous ones because nothing fails. `\d`, `\w`, `\s` and `\b` are ASCII-only: `\d+` on `a٣٤5 3` finds only `5`, `\p{Nd}+` finds `٣٤5` and `3`, `\w+` on `café` finds `caf`. `$` without `m` matches only at the very end (`^\d+$` does not match `12\n`; use `\n?\z` to allow one final newline). Matching is leftmost-first like Perl (`a|ab` on `ab` gives `a`) until you call `Longest()`; `(?U)` swaps greedy and lazy (`(?U)a+` on `aaa` gives `a`).
  • Some Perl-looking syntax compiles but means something else: `[[.a.]]` and `[[=a=]]` are parsed as plain character sets followed by `]`, not collating elements; `a{,3}` and `a{` are literal text; duplicate group names such as `(?P<y>a)(?P<y>b)` are accepted. `FindAll` skips an empty match that touches the previous match: `a*` on `baaab` gives indexes `[[0 0] [1 4] [5 5]]` and `ReplaceAllString(…, "-")` gives `-b-b-`.

Go sketch

Go
import (
    "errors"
    "fmt"
    "regexp"
    "regexp/syntax"
)

// check compiles pattern and reports the syntax.Error code and offending text.
func check(pattern string) string {
    _, err := regexp.Compile(pattern)
    if err == nil {
        return "ok"
    }
    var se *syntax.Error
    if errors.As(err, &se) {
        return fmt.Sprintf("%s: %s", se.Code, se.Expr)
    }
    return err.Error()
}

func demo() {
    for _, p := range []string{`foo(?=bar)`, `(?<=a)b`, `(a)\1`, `a*+`, `\Z`, `a{1001}`, `(?P<y>a)`} {
        fmt.Printf("%-12s %s\n", p, check(p))
    }
    // foo(?=bar)   invalid or unsupported Perl syntax: (?=
    // (?<=a)b      invalid named capture: (?<=a)b
    // (a)\1        invalid escape sequence: \1
    // a*+          invalid nested repetition operator: *+
    // \Z           invalid escape sequence: \Z
    // a{1001}      invalid repeat count: {1001}
    // (?P<y>a)     ok
}

Behaviour that compiles fine but differs from Perl-style engines (outputs from Go 1.24.7).

Go
import (
    "fmt"
    "regexp"
)

func semantics() {
    // \d, \w and \b are ASCII-only; use \p{Nd} / [\p{L}\p{N}_] for Unicode.
    fmt.Printf("%q\n", regexp.MustCompile(`\d+`).FindAllString("a٣٤5 3", -1))     // ["5"]
    fmt.Printf("%q\n", regexp.MustCompile(`\p{Nd}+`).FindAllString("a٣٤5 3", -1)) // ["٣٤5" "3"]
    fmt.Printf("%q\n", regexp.MustCompile(`\w+`).FindAllString("café", -1))       // ["caf"]

    // Leftmost-first by default; Longest() switches to leftmost-longest.
    re := regexp.MustCompile(`a|ab`)
    fmt.Println(re.FindString("ab")) // a
    re.Longest()
    fmt.Println(re.FindString("ab")) // ab

    // (?U) swaps greedy and lazy.
    fmt.Println(regexp.MustCompile(`(?U)a+`).FindString("aaa"))  // a
    fmt.Println(regexp.MustCompile(`(?U)a+?`).FindString("aaa")) // aaa

    // An empty match right after a previous match is skipped.
    fmt.Println(regexp.MustCompile(`a*`).FindAllStringIndex("baaab", -1))       // [[0 0] [1 4] [5 5]]
    fmt.Printf("%q\n", regexp.MustCompile(`a*`).ReplaceAllString("baaab", "-")) // "-b-b-"
}

In practice

  • Go regexp — Documents RE2 syntax and states that matching is guaranteed to run in time linear in the size of the input; the missing features are the price of that guarantee. `regexp/syntax` lists the supported grammar.
  • RE2 — The C++ library the syntax comes from; it rejects the same backtracking-only constructs by design (per its syntax documentation; the C++ library was not run here).
  • ripgrep — The default engine refuses lookaround and backreferences: `rg 'foo(?=bar)'` exits with 2 and `error: look-around, including look-ahead and look-behind, is not supported` (observed on 14.1.0). `rg -P` switches to PCRE2, where `foo(?=bar)` with `-o` prints `foo`.
  • Prometheus — Relabeling and label matchers take RE2 (Go regexp) syntax according to its documentation (not run here), so a lookahead copied into a `relabel_configs` regex fails when the configuration is loaded.

Trade-offs

Pros

  • Unsupported syntax fails at compile time with a position-like fragment, so a bad pattern in a package-level `MustCompile` is caught at startup rather than on one rare input.
  • Dropping backtracking features is what gives the linear-time guarantee, so the same pattern cannot hang a server on adversarial input.
  • Every error carries a `syntax.ErrorCode` string, reachable with `errors.As`, so callers need not parse the message text.

Cons

  • Messages name the parser state, not the feature: lookbehind reads `invalid named capture` and a backreference reads `invalid escape sequence`, which are hard to search for.
  • Rewrites are not mechanical: atomic groups and lookarounds can change what matches, and some constructs (recursion, `\X`) have no regular equivalent.
  • The silent differences (ASCII-only `\d`, `\w`, `\b`; `$` without a trailing-newline allowance; leftmost-first alternation) pass compilation and show up as wrong matches.

Five ways to get lookahead and lookbehind behaviour without them: capture groups, two-pass matching, manual boundary checks, chunking, and regexp2, each tested against Python and Node.

The problem

A pattern like `(?<=,)\w+(?=,)` or `foo(?!bar)` is routine in Python or JavaScript and impossible in Go. The common advice, wrapping the context in a capture group, works only until two matches share context: the group consumes the text, so the next search starts after it. Five rewrites cover the practical cases; each one below was run on Go 1.24.7 and checked against Python 3.13 and Node 22 (and, for the lookaround forms, `regexp2`), because a rewrite that looks equivalent can quietly return different matches.

How it works

  • Capture group: move the context into the pattern and read only the group. `(?<=\$)\d+` becomes `\$(\d+)`, and `FindAllStringSubmatch` on `$5 and $10, 20 or $3` gives `5`, `10`, `3`, the same as Python. For replacements, put the context back: `foo(bar)` replaced with `X$1` turns `foobar foo foobar` into `Xbar foo Xbar`, matching `re.sub(r'foo(?=bar)', 'X', …)`.
  • Side effect: the consumed context belongs to the match, so the next search starts after it and neighbours that shared it are lost. `(?<=,)\w+(?=,)` on `a,b,c,d` returns `b` and `c` in Python, Node and regexp2, but `,(\w+),` returns only `b`, because the comma between `b` and `c` was eaten. `a(?=a)` finds 3 matches in `aaaa`; `(a)a` finds 2 (`[[0 2] [2 4]]`).
  • Fix for the side effect: resume the search at the end of group 1 instead of the end of the match. `betweenResume` loops on `s[pos:]` and sets `pos += m[3]`, returning `b`, `c` as Python does. Slicing creates a new input, so `^`, `\b` and `(?m)^` treat the slice start as the start of the text, and `regexp` has no start-offset parameter to avoid that.
  • Two-pass for lookahead: find the core with one regexp, then test the following text with `strings.HasPrefix(s[end:], …)` or a second `^`-anchored regexp. `fooNotBar` on `foobar foo foofoobar` returns offsets `7` and `11`, the same as `foo(?!bar)` in Python.
  • Manual boundary check for lookbehind: find candidates, then inspect the rune before each start with `utf8.DecodeLastRuneInString(s[:start])`. A rejected candidate must restart one rune after its start, not at its end: for `(?<!x)\d\d` on `x123`, filtering `FindAll` results returns nothing because `12` is rejected and hides `23`, while the retry loop returns `23` as Python, Node and regexp2 do. On `x12 345 x99 6789` it returns `34`, `67`, `89`.
  • Chunking: when the context is bounded by a record, split first and apply plain tests per record. `^(?!.*DEBUG).*ERROR` becomes, per line, `MatchString("ERROR") && !strings.Contains(line, "DEBUG")`; on `ERROR a`, `DEBUG ERROR b`, `ok`, `ERROR c` it keeps `ERROR a` and `ERROR c`, as Python's `re.M` version does. Only split on natural boundaries, since a cut inside a match changes the result.
  • `github.com/dlclark/regexp2` v1.12.0 (fetched with `go get` through the module proxy here) is a backtracking, .NET-style engine that runs the original patterns: lookbehind (even variable-length `(?<=a+)b`), `(\w)\1` (matches `ll` in `hello`), atomic `(?>a+)b` and `GroupByName` all worked. The API differs from `regexp` (`MatchString` returns `(bool, error)`; iterate with `FindStringMatch` and `FindNextMatch`).
  • regexp2 gives up the guarantee. `regexp2.DefaultMatchTimeout` printed `2562047h47m16.854775807s`, effectively no timeout, so `^(a+)+$` on 40 `a` characters plus `b` ran for more than 30 s (stopped). With `MatchTimeout = 200 * time.Millisecond` it returned the error `match timeout after 200ms on input …`. The `regexp2.RE2` option only changes parsing and did not help: `(?<=a)b` still compiled and the same input still hit the timeout.
  • Compile errors are the early warning: use `regexp.Compile` for patterns from config and wrap with `%w` (`fmt.Errorf("filter %q: %w", name, err)`); `errors.As` still reaches the `*syntax.Error` and its `Code`. Reserve `MustCompile` for literals in source.

Examples

Go
import (
    "fmt"
    "regexp"
    "strings"
    "unicode/utf8"
)

// (?<=\$)\d+  ->  capture group: the "$" is consumed, only group 1 is used.
var priceRe = regexp.MustCompile(`\$(\d+)`)

func prices(s string) []string {
    var out []string
    for _, m := range priceRe.FindAllStringSubmatch(s, -1) {
        out = append(out, m[1])
    }
    return out
}

// (?<=,)\w+(?=,)  ->  naive rewrite: both commas are consumed, so the comma
// shared by two neighbours is gone before the next search starts.
var betweenRe = regexp.MustCompile(`,(\w+),`)

func betweenNaive(s string) []string {
    var out []string
    for _, m := range betweenRe.FindAllStringSubmatch(s, -1) {
        out = append(out, m[1])
    }
    return out
}

// Same rewrite, but resume right after group 1 so the trailing "," can start
// the next match. s[pos:] is a new input: ^ and \b see its start as text start.
func betweenResume(s string) []string {
    var out []string
    for pos := 0; pos < len(s); {
        m := betweenRe.FindStringSubmatchIndex(s[pos:])
        if m == nil {
            break
        }
        out = append(out, s[pos+m[2]:pos+m[3]])
        pos += m[3]
    }
    return out
}

// foo(?!bar)  ->  two passes: find "foo", then test what follows it.
var fooRe = regexp.MustCompile(`foo`)

func fooNotBar(s string) []int {
    var out []int
    for _, m := range fooRe.FindAllStringIndex(s, -1) {
        if !strings.HasPrefix(s[m[1]:], "bar") {
            out = append(out, m[0])
        }
    }
    return out
}

// (?<!x)\d\d  ->  manual boundary check. A rejected candidate must not hide an
// overlapping one, so retry one rune after its start instead of at its end.
var twoDigits = regexp.MustCompile(`\d\d`)

func twoDigitsNotAfterX(s string) []string {
    var out []string
    for pos := 0; pos < len(s); {
        loc := twoDigits.FindStringIndex(s[pos:])
        if loc == nil {
            break
        }
        start, end := pos+loc[0], pos+loc[1]
        if r, _ := utf8.DecodeLastRuneInString(s[:start]); start > 0 && r == 'x' {
            _, size := utf8.DecodeRuneInString(s[start:])
            pos = start + size
            continue
        }
        out = append(out, s[start:end])
        pos = end
    }
    return out
}

// ^(?!.*DEBUG).*ERROR  ->  chunking: split into lines, run plain tests per line.
var errorRe = regexp.MustCompile(`ERROR`)

func errorsWithoutDebug(text string) []string {
    var out []string
    for _, line := range strings.Split(text, "\n") {
        if errorRe.MatchString(line) && !strings.Contains(line, "DEBUG") {
            out = append(out, line)
        }
    }
    return out
}

// A pattern that comes from config: Compile, then wrap with %w so callers can
// still reach the *syntax.Error with errors.As.
func compileFilter(name, pattern string) (*regexp.Regexp, error) {
    re, err := regexp.Compile(pattern)
    if err != nil {
        return nil, fmt.Errorf("filter %q: %w", name, err)
    }
    return re, nil
}

func demo() {
    fmt.Printf("%q\n", prices("$5 and $10, 20 or $3"))                            // ["5" "10" "3"]
    fmt.Printf("%q\n", betweenNaive("a,b,c,d"))                                   // ["b"]
    fmt.Printf("%q\n", betweenResume("a,b,c,d"))                                  // ["b" "c"]
    fmt.Println(fooNotBar("foobar foo foofoobar"))                                // [7 11]
    fmt.Printf("%q\n", twoDigitsNotAfterX("x12 345 x99 6789"))                    // ["34" "67" "89"]
    fmt.Printf("%q\n", errorsWithoutDebug("ERROR a\nDEBUG ERROR b\nok\nERROR c")) // ["ERROR a" "ERROR c"]
}

Optional dependency for patterns that must run unchanged; always set a timeout.

bash
go get github.com/dlclark/regexp2@v1.12.0
# regexp2: re, _ := regexp2.Compile(`(?<=,)\w+(?=,)`, regexp2.None)
#          m, _ := re.FindStringMatch("a,b,c,d")   // "b"
#          m, _ = re.FindNextMatch(m)               // "c"
# Always set re.MatchTimeout for patterns you do not control.

In practice

  • Go regexp — Has no lookaround by design, so ports of PCRE or JavaScript patterns use the capture-group, two-pass or manual-check rewrites shown here.
  • dlclark/regexp2 — A Go port of the .NET regex engine (v1.12.0 observed) used when a pattern must run unchanged. It backtracks and has no default match timeout.
  • ripgrep — Keeps its default engine lookaround-free and offers `-P` (PCRE2) for the rest; the same split between a linear engine and a backtracking opt-in that Go makes with regexp2.
  • Python re — Used as the reference in these tests: Python 3.13 `re.findall(r'(?<=,)\w+(?=,)', 'a,b,c,d')` returns `['b', 'c']`, and Node 22 returns the same.

Trade-offs

Pros

  • Capture groups need no extra code and keep linear-time matching; most lookarounds are one-sided and non-overlapping, where they are enough.
  • Two-pass and manual checks make the context rule explicit and testable, and handle negative lookaround, which capture groups cannot express.
  • Chunking bounds memory as well as context, so it suits log and stream processing.

Cons

  • Every rewrite is more code than one pattern, and the overlap and slice-anchor pitfalls only show up on specific inputs; test against a reference engine.
  • The resume trick re-slices the input, so `^`, `\b` and `(?m)^` change meaning on the remainder.
  • regexp2 restores the original patterns but not the guarantee: it needs an explicit timeout, a new dependency and a different API, and its `RE2` option does not make it linear.

Compile vs MustCompile, the Find/FindAll/String/Submatch/Index naming scheme, Replace and its $ templates, Split, QuoteMeta, Longest and the introspection methods.

The problem

The regexp package has dozens of methods, but they are generated from a naming scheme and a handful of rules: how a pattern is compiled, what a miss returns, how groups and offsets are reported, and how replacement templates expand. Most bugs come from the rules, not the names: an empty match looks like no match, `$1_x` silently means a different group, and `Longest` is a configuration call on a shared object.

How it works

  • Naming: `Find` + optional `All` + optional `String` + optional `Submatch` + optional `Index`. `String` forms take and return `string`, the others `[]byte`; `All` forms take `n` (negative = all, positive = at most `n`, zero = `nil`, observed); `Submatch` adds the groups; `Index` returns byte offsets instead of text. The table `go-regexp-functions` lists every combination.
  • `regexp.MustCompile` panics on a bad pattern with `regexp: Compile(`(?<=a)b`): error parsing regexp: invalid named capture: `(?<=a)b``; use it for literals as package-level variables. Use `regexp.Compile` when the pattern comes from config or users. The package functions `regexp.MatchString(pattern, s)` compile on every call.
  • Misses are `nil` or `""`. `FindString` returns `""` both for no match and for a match that is empty, so use `FindStringIndex` (`nil` on a miss) or `MatchString` when the difference matters. `FindStringSubmatch` returns `NumSubexp()+1` strings (index 0 is the whole match); a group that did not take part is `""`, and in the Index form it is `-1 -1`: `(a)|(b)` on `b` gives `["b" "" "b"]` and `[0 1 -1 -1 0 1]`.
  • `ReplaceAllString` expands `$1`, `${1}`, `$name` and `${name}`; `$$` is a literal `$`. The name is the longest run of letters, digits and underscore, so `$1_x` means the group named `1_x` and expands to nothing; write `${1}_x` (gives `bob_x`). `\1` is not special, a nonexistent group such as `$3` expands to nothing, and `ReplaceAllLiteralString` inserts the replacement verbatim.
  • `ReplaceAllStringFunc` passes only the matched text to the function, never the groups. When you need groups, take `FindStringSubmatchIndex` and call `ExpandString(nil, "$2 <- $1", s, m)` (gives `example <- bob`), or rebuild the string from the offsets.
  • `Split(s, n)` returns the text between matches and keeps trailing empties: `,` on `a,b,,c,` gives `["a" "b" "" "c" ""]`, `n = 2` gives `["a" "b,,c,"]`, `n = 0` gives `nil`, no match gives `[s]`. An empty-matching separator splits between characters: `x*` on `abc` gives `["a" "b" "c"]`.
  • `regexp.QuoteMeta` escapes `\.+*?()|[]{}^$`, so `a.b*c[d]` becomes `a\.b\*c\[d\]`; it leaves `-`, `_`, space and non-ASCII text alone, which is correct outside a character class. Use it when embedding user text in a pattern.
  • `Longest()` and `CompilePOSIX` switch to leftmost-longest matching (`a|ab` on `ab`: `a` by default, `ab` after the switch). A `Regexp` is safe for concurrent use except for configuration methods such as `Longest`, so call it once at construction, before sharing.
  • Introspection: `NumSubexp()`, `SubexpNames()`, `SubexpIndex(name)` (-1 if absent), `LiteralPrefix()` (`abc+d` gives `abc`, `false`; `abc` gives `abc`, `true`), `String()`. Reader forms (`MatchReader`, `FindReaderIndex`) scan an `io.RuneReader` without loading it; `FindReaderIndex` for `b+` over `aabbb` gives `[2 5]`.

Go sketch

Go
import (
    "fmt"
    "regexp"
    "strings"
)

// Package level: compile once. MustCompile panics on a bad pattern, so use it
// only for literals; use Compile for patterns that come from users or config.
var dateRe = regexp.MustCompile(`(\d{4})-(\d{2})(-(\d{2}))?`)

func tour() {
    s := "on 2026-10 and 2026-10-11."
    fmt.Println(dateRe.MatchString(s))                                        // true
    fmt.Printf("%q\n", dateRe.FindString(s))                                  // "2026-10"
    fmt.Println(dateRe.FindStringIndex(s))                                    // [3 10]
    fmt.Printf("%q\n", dateRe.FindStringSubmatch(s))                          // ["2026-10" "2026" "10" "" ""]
    fmt.Println(dateRe.FindStringSubmatchIndex(s))                            // [3 10 3 7 8 10 -1 -1 -1 -1]
    fmt.Printf("%q\n", dateRe.FindAllString(s, -1))                           // ["2026-10" "2026-10-11"]
    fmt.Printf("%q\n", dateRe.FindAllStringSubmatch(s, -1)[1])                // ["2026-10-11" "2026" "10" "-11" "11"]
    fmt.Println(dateRe.NumSubexp())                                           // 4
    fmt.Println(dateRe.ReplaceAllString(s, "${2}/${1}"))                      // on 10/2026 and 10/2026.
    fmt.Println(dateRe.ReplaceAllLiteralString(s, "${2}/${1}"))               // on ${2}/${1} and ${2}/${1}.
    fmt.Println(dateRe.ReplaceAllStringFunc(s, strings.ToUpper))              // on 2026-10 and 2026-10-11.
    fmt.Printf("%q\n", regexp.MustCompile(`\s*,\s*`).Split("a , b,c ,d", -1)) // ["a" "b" "c" "d"]
    fmt.Println(regexp.QuoteMeta(`a.b*c[d]`))                                 // a\.b\*c\[d\]
}

In practice

  • Go regexp — The standard library implementation; the method families above are generated from one scheme, and `Regexp` values are meant to be built once and shared.
  • Prometheus — Its configuration regexes (relabeling, label matchers) are compiled with Go regexp according to its documentation (not run here), including the `$1` / `${1}` replacement templates.
  • Pitfall: ReplaceAllString templates — `ReplaceAllString(s, "$1_suffix")` expands the group named `1_suffix`, which does not exist, and silently produces an empty string. Write `${1}_suffix`.
  • Pitfall: FindString on optional text — `FindString` with the pattern `a*` on the text `b` returns `""`, the same value a miss gives. Check `FindStringIndex` or `MatchString` when empty is a legal answer.

Trade-offs

Pros

  • One naming scheme covers text or bytes, first or all, groups or offsets, so the right method can be derived instead of memorized.
  • A compiled `Regexp` is safe to share between goroutines, and the offset forms let you slice the original input without copies.
  • `Compile` / `MustCompile` split makes the failure mode explicit: panic at startup for literals, an error for dynamic patterns.

Cons

  • No start-offset or named-group-map helper: resuming a search or collecting named groups means slicing the input and writing small helpers.
  • `$` templates, empty-versus-miss results and unmatched groups reported as `""` are easy to misread, and nothing warns about them.
  • The large method surface (dozens of Find, Replace and Match variants) is mostly mechanical, which makes documentation tables more useful than prose.

(?P<name>) and (?<name>), SubexpNames and SubexpIndex, a map[string]string helper, unmatched groups, and the ${name} vs $name1 replacement trap.

The problem

Numbered groups break the moment someone adds a group in front. Named groups make extraction readable, but each engine spells them differently, and Go's API gives you names and indexes rather than a ready map. The other trap is in replacement templates, where `$name1` is parsed as one long name.

How it works

  • Go 1.24.7 accepts both `(?P<name>re)` and `(?<name>re)`; both appear in the regexp/syntax documentation. The `(?<name>` spelling arrived in Go 1.22 (Go 1.21.13 rejected it with `invalid or unsupported Perl syntax: `(?<``, Go 1.22.0 compiled it; the Go 1.22 release notes do not mention it), so code that must build on older toolchains should use `(?P<name>`. `(?'name're)` is rejected with `invalid or unsupported Perl syntax: `(?'``.
  • Names must be word characters: `(?P<n!>a)` and `(?<n-1>a)` fail with `invalid named capture`, `(?P<>a)` fails the same way, while `(?<1>a)` and `(?P<1y>a)` compile. Duplicate names are accepted by Go (`(?P<y>a)(?P<y>b)` has `SubexpNames()` of `["" "y" "y"]`), whereas Python 3.13 reports `redefinition of group name` and Node 22 reports `Duplicate capture group name`.
  • Named groups are numbered together with unnamed ones from left to right. For `(?P<year>\d{4})-(?P<month>\d{2})(-(?P<day>\d{2}))?`, `SubexpNames()` is `["" "year" "month" "" "day"]`: index 0 is the whole match, unnamed groups give `""`, and `NumSubexp()` is 4.
  • `SubexpIndex(name)` (Go 1.15) returns the index or -1 for an unknown name; with duplicate names it returns the leftmost. Use it to look up once, at start-up, instead of hard-coding indexes: `idx := re.SubexpIndex("path")` and then `m[idx]`.
  • There is no built-in map. `namedGroups` loops over `SubexpNames()` with `FindStringSubmatchIndex` and skips groups whose offset is -1, because `FindStringSubmatch` returns `""` for a group that did not take part and for one that matched empty. For `(?P<a>x)|(?P<b>y)` on `y`, the submatch is `["y" "" "y"]` and the indexes are `[0 1 -1 -1 0 1]`.
  • Replacement templates accept `$name` and `${name}`, where the name is the longest run of letters, digits and underscore. On `bob@example.com` with groups `user` and `host`, the template `${host}1 $host1 ${user}` gives `example1 bob`: `$host1` is the group `host1`, which does not exist, and expands to nothing. Always use braces when a word character follows.
  • Cross-engine spelling: Go accepts `(?P<n>)` and `(?<n>)`; Python 3.13 accepts only `(?P<n>)` and reports `unknown extension ?<n` for the other; Node 22 accepts only `(?<n>)` and reports `Invalid group` for `(?P<n>)`. No single spelling works in Python and JavaScript, which matters for patterns shared across services. `grep -P` accepted `(?<y>a)` and Perl accepted both here.
  • Go has no named backreference: `(?P=name)` and `\k<name>` fail to compile (see `re2-unsupported-syntax`); compare the captured strings in code.

Go sketch

Go
import (
    "fmt"
    "regexp"
)

var logRe = regexp.MustCompile(`(?P<method>[A-Z]+) (?P<path>\S+)(?: HTTP/(?<proto>[\d.]+))?`)

// namedGroups maps each named group to its text. A group that did not take
// part in the match is absent from the map, unlike FindStringSubmatch, which
// returns "" for it.
func namedGroups(re *regexp.Regexp, s string) map[string]string {
    idx := re.FindStringSubmatchIndex(s)
    if idx == nil {
        return nil
    }
    out := make(map[string]string)
    for i, name := range re.SubexpNames() {
        if name == "" || idx[2*i] < 0 {
            continue
        }
        out[name] = s[idx[2*i]:idx[2*i+1]]
    }
    return out
}

func demo() {
    fmt.Println(namedGroups(logRe, "GET /a HTTP/1.1")) // map[method:GET path:/a proto:1.1]
    fmt.Println(namedGroups(logRe, "GET /a"))          // map[method:GET path:/a]
    fmt.Println(logRe.SubexpIndex("path"))             // 2

    // In a template, $name1 means the group called "name1", not "name" + "1".
    re := regexp.MustCompile(`(?P<user>\w+)@(?P<host>\w+)\.com`)
    fmt.Printf("%q\n", re.ReplaceAllString("bob@example.com", "${host}1 $host1 ${user}")) // "example1  bob"
}

In practice

  • Go regexp — `SubexpNames` and `SubexpIndex` are the whole named-group API; the map helper above is the usual 10-line wrapper.
  • Grafana Loki — LogQL's `regexp` parser stage extracts labels from named capture groups written in RE2 syntax, per its documentation (not run here).
  • Python re — Accepts only `(?P<name>)` and exposes `m.group('name')` and `m.groupdict()` (3.13: `(?<y>a)` fails with `unknown extension ?<y`).
  • V8 Irregexp — Node 22 accepts only `(?<name>)`, exposes `match.groups.name`, and rejects duplicate names with `Duplicate capture group name`.

Trade-offs

Pros

  • Names survive refactoring: adding a group no longer shifts every index, and a lookup at start-up replaces magic numbers.
  • Go accepts both common spellings, so patterns from Python (`(?P<n>)`) and JavaScript (`(?<n>)`) usually compile unchanged.
  • Index forms report unmatched groups as -1, so optional groups are distinguishable from empty ones.

Cons

  • No ready-made map or struct binding: each project writes the helper, and the `FindStringSubmatch` shortcut hides unmatched groups as `""`.
  • Duplicate names are silently accepted and only the leftmost is visible through `SubexpIndex`.
  • `$name1` in templates is a silent footgun; the same pattern behaves differently when spelled with braces.

Linear-time matching, why compiling in a loop is slow, benchmarks against strings.Contains/Cut/HasPrefix, compile-time limits, and the limits of the no-ReDoS promise.

The problem

Go's regexp is slower than strings functions for simple jobs, much faster to fail than a backtracking engine for hard ones, and very easy to use in a way that makes it slow: compiling inside a function that runs per request. Knowing which of the three situations you are in decides whether a regex is the right tool, and where the real limits of the "no ReDoS" promise are.

How it works

  • The package documentation guarantees matching in time linear in the size of the input. Observed: `(a+)+$` on `a` repeated n times plus `b`: for Go, doubling n from 100,000 up to 6,400,000 multiplied the time by about 1.4 to 2 each step (an occasional step ran higher from timer and GC noise). For Python 3.13 (n from 16 to 26) every extra character roughly doubled the time (about 4 times per two characters). Node 22 (n from 18 to 27) also doubled per extra character. Absolute times are left out on purpose.
  • Linear in input does not mean cheap: cost also scales with the size of the compiled program. Go caps it at compile time: repeat counts above 1000 (`invalid repeat count`), nested repeat products above 1000, `expression too large` (5000 copies of `\pL{1000}`) and `expression nests too deeply` (1000 groups). These caps matter when patterns come from users.
  • There is no timeout or cancellation parameter on any `regexp` method, so a large input with a large user-supplied pattern is bounded only by the input size and program size. Cap the pattern length (`compileUser` rejects over 1024 bytes in the sketch), cap the input, and run untrusted work with its own deadline at the call level.
  • Compile once. `BenchmarkCompileInLoop` (`MustCompile` inside the loop) reported 37 allocs/op and about 2400 B/op, versus 0 allocs/op for a package-level variable; the loop version was roughly two orders of magnitude slower (observed on one machine, trend only). The package function `regexp.MatchString(pattern, s)` showed the same 37 allocs/op because it compiles every call.
  • Share the compiled value: a `*Regexp` is safe for concurrent use except configuration methods such as `Longest`. Put it in a package variable or a struct field, and cache compiled user patterns in a map or `sync.Map` keyed by the pattern string.
  • For simple shapes, `strings` wins. On the same machine: a prebuilt `^GET ` match against `strings.HasPrefix` was far faster for the latter (the compiler can fold a constant prefix test); `/api/` in a request line via regexp was about an order of magnitude slower than `strings.Contains`; extracting `verbose=1` with `FindStringSubmatch` cost 2 allocs/op where `strings.Cut` cost 0 and was tens of times faster. Reach for `HasPrefix`, `Contains`, `Cut`, `strconv` and `net/url` first.
  • Shape the pattern for the engine. `MatchString` allocated 0 and `FindStringSubmatch` 2 for the same pattern. A leading `.*` (`.*example`) was about ten times slower than the bare literal `example` on a 60-byte input, because the literal can be found with a fast substring search first (`LiteralPrefix` reports the prefix). Anchor with `^` when you can, avoid leading `.*`, and ask for groups only when you use them.
  • Go picks its matcher from the pattern and input: a one-pass matcher, a bounded backtracker for small cases, or the NFA simulation (files `onepass.go`, `backtrack.go`, `exec.go` in the standard library). All three keep the linear bound; none supports lookaround, which is why it is absent.
  • regexp2 (the .NET-style engine) is a different trade: `^(a+)+$` on 40 `a` plus `b` ran past 30 s without a timeout and returned `match timeout after 200ms` with `MatchTimeout` set, so it does not inherit the guarantee (see `lookaround-rewrites-in-go`). Profile before guessing: `go test -bench -benchmem`, then pprof shows `regexp.(*Regexp).doExecute` or compile in the top frames.

Examples

Go
import (
    "fmt"
    "regexp"
    "strings"
    "testing"
)

const reqLine = "GET /api/v1/users/42?verbose=1 HTTP/1.1"

var (
    getRe = regexp.MustCompile(`^GET `)
    kvRe  = regexp.MustCompile(`^([^=]+)=(.*)$`)
    sink  string
    ok    bool
)

func BenchmarkCompileInLoop(b *testing.B) {
    for i := 0; i < b.N; i++ {
        re := regexp.MustCompile(`^GET `)
        ok = re.MatchString(reqLine)
    }
}

func BenchmarkPackageLevel(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ok = getRe.MatchString(reqLine)
    }
}

func BenchmarkHasPrefix(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ok = strings.HasPrefix(reqLine, "GET ")
    }
}

func BenchmarkKeyValueRegexp(b *testing.B) {
    for i := 0; i < b.N; i++ {
        sink = kvRe.FindStringSubmatch("verbose=1")[2]
    }
}

func BenchmarkKeyValueCut(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _, sink, _ = strings.Cut("verbose=1", "=")
    }
}

var (
    dotStarRe = regexp.MustCompile(`.*example`)
    literalRe = regexp.MustCompile(`example`)
)

const bodyText = "contact: bob@example.com for details about the report, thanks"

// A leading .* forces the engine to try every start; a bare literal can be
// found with a fast substring search first.
func BenchmarkLeadingDotStar(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ok = dotStarRe.MatchString(bodyText)
    }
}

func BenchmarkBareLiteral(b *testing.B) {
    for i := 0; i < b.N; i++ {
        ok = literalRe.MatchString(bodyText)
    }
}

// compileUser guards a pattern that comes from outside: bound its length, and
// let Compile's own limits reject huge repeats and deep nesting.
func compileUser(pattern string) (*regexp.Regexp, error) {
    if len(pattern) > 1024 {
        return nil, fmt.Errorf("pattern too long: %d bytes", len(pattern))
    }
    return regexp.Compile(pattern)
}

Run the benchmarks above; allocations per operation are stable across machines, times are not.

bash
go test -bench . -benchmem -count=1
# Observed allocations per operation on Go 1.24.7 (times are not shown on purpose):
# BenchmarkCompileInLoop     37 allocs/op   regexp.MustCompile inside the loop
# BenchmarkPackageLevel       0 allocs/op   package-level MustCompile
# BenchmarkHasPrefix          0 allocs/op   strings.HasPrefix
# BenchmarkKeyValueRegexp     2 allocs/op   FindStringSubmatch
# BenchmarkKeyValueCut        0 allocs/op   strings.Cut

Go: time roughly doubles when the input doubles (ratios mostly 1.4 to 2.3 observed, with an occasional noisy step).

Go
import (
    "fmt"
    "regexp"
    "strings"
    "time"
)

// Doubling the input roughly doubles the time: (a+)+$ is not exponential here.
func linearTrend() {
    re := regexp.MustCompile(`(a+)+$`)
    var prev time.Duration
    for n := 100_000; n <= 1_600_000; n *= 2 {
        s := strings.Repeat("a", n) + "b"
        start := time.Now()
        re.MatchString(s)
        d := time.Since(start)
        if prev > 0 {
            fmt.Printf("n=%d time ratio vs half size: %.1f\n", n, float64(d)/float64(prev))
        }
        prev = d
    }
}

Python 3.13 for contrast: each two extra characters multiplied the time by about 4 (3.2 to 4.2 observed).

Python
import re
import time

pattern = re.compile(r"(a+)+$")
previous = None
for n in range(16, 27, 2):
    text = "a" * n + "b"
    start = time.perf_counter()
    pattern.search(text)
    elapsed = time.perf_counter() - start
    if previous:
        print(f"n={n} time vs n-2: x{elapsed / previous:.1f}")
    previous = elapsed

In practice

  • Go regexp — Documents linear-time matching and rejects oversized patterns at compile time; the cost model is `len(input) * len(program)`, not exponential.
  • RE2 — The design this behaviour comes from: automaton-based matching with a bounded memory and time model (per the RE2 documentation; the C++ library was not run here).
  • Python re — A backtracking engine: `(a+)+$` roughly doubled in time for every added `a` on 3.13, the contrast case in the sketch.
  • pprof — Profiles from `go test -cpuprofile` or a live service show regexp compile and execute frames, which is how a compile-in-a-handler bug is usually found.

Trade-offs

Pros

  • Predictable worst case: time scales with input and program size, so a bad pattern or hostile input degrades smoothly instead of hanging a process.
  • A prebuilt `*Regexp` has zero allocations for `MatchString`, is concurrency-safe and needs no locking.
  • Compile-time caps turn runaway patterns into errors at load time.

Cons

  • Slower than `strings.HasPrefix`, `Contains` or `Cut` for fixed text, and `FindStringSubmatch` allocates.
  • No per-call timeout or cancellation, and no lookaround or backreferences to make patterns shorter.
  • A mistake that is easy to make and invisible in review: `MustCompile` inside a function that runs per request.

Common patterns

Validation anchors the whole string (`^…$`, full match) and extraction scans for pieces (`FindAll`, `\b`); a regex can show that an email or ID has an acceptable shape, never that it is valid or deliverable.

The problem

One pattern tends to end up doing two different jobs. Validating asks "is this whole string acceptable?" and needs anchors; extracting asks "what acceptable things are inside this text?" and must not have them. Mixing the two gives either false accepts (`junk a@b.co junk` passes an unanchored check) or no matches at all. Underneath is a harder limit: a regex checks the shape of a string, not whether the thing it names is valid. Whether an email is deliverable, a URL resolves or a date exists is answered by a parser, a checksum or a round trip.

How it works

  • Validate means whole string. Anchor both ends (`^…$`) and ask for a match: Go has no full-match call, so anchor and use `MatchString`; JavaScript uses `re.test(s)` with anchors; Python has `re.fullmatch`. Extract means scan: no anchors, `FindAllString` / `matchAll` / `finditer`, plus a boundary (`\b` or an explicit delimiter class) so a match cannot start or end inside a longer token.
  • Observed on Go 1.24 and Node 22 (identical results): the anchored email shape in the snippet accepts 6 of 6 (`a@b.co`, `first.last+tag@example.com`, `user_1@sub.example.org`, `x@a-b.io`, `UPPER@EXAMPLE.COM`, `a..b@x.com`) and rejects 10 of 10 (`plain`, `@no.local`, `a@b`, `a@@b.com`, `a b@c.com`, `a@b.c`, `a@b.com` plus a newline, `"q u"@x.com`, `a@b.com.`, `me@例え.jp`).
  • The extraction form (the email pattern of the Regex Snippets tool, which this group starts from) is not a validator: `MatchString("junk a@b.co junk")` is true because any substring qualifies. On `Contact dev@birdor.com or support@example.org.` FindAll returns exactly the two addresses, the final period excluded by the trailing `\b`; `grep -oE` prints the same two lines (GNU grep 3.11). Copy-ready versions of many more patterns live in the Regex Snippets tool (site path /tools/regex-snippets); this group keeps only those that carry a pitfall worth explaining.
  • Trailing newline: without the multiline flag, `$` matches only at the very end of the text on Go and JavaScript, so `a@b.com` followed by a newline is rejected. Python 3.13 `re.search` with the same anchors accepts it; `re.fullmatch` and `\Z` reject it. Digits differ too: `^\d{6}$` accepts the fullwidth `200000` on Python 3.13 and rejects it on Go and Node.
  • Shape is a policy, not a fact about email. The anchored pattern accepts `a..b@x.com` (net/mail rejects it with `mail: missing '@' or angle-addr`) and rejects the quoted local part `"q u"@x.com` and an internationalised domain such as `me@例え.jp` (it would have to be written in punycode, `xn--…`). It does not implement RFC 5322 and should not be described as doing so.
  • `net/mail.ParseAddress` follows the RFC address grammar more closely but answers a different question: it accepts `a@b` (no dot) and `Name <a@b.com>` and returns the bare address in `.Address`, so compare that with the input if only a plain address is wanted. Even a perfect parse proves syntax, not that the mailbox exists; only a confirmation message does.
  • What a regex can express: character sets, length ranges, separators, per-field numeric ranges (0-255, 01-12). What it cannot: arithmetic across fields (days per month, leap years), checksums (Luhn, the ID-card check digit), whether something is allocated or deliverable, DNS, or a total length that spans repeated groups (the 253-character hostname limit). The four other entries in this group each draw that line for one family of patterns.
  • Keep each pattern in one place: a package-level `regexp.MustCompile` named for its job (`emailShape`, `emailFind`), with its accept and reject corpus beside it as a table-driven test.

Examples

Go
import (
    "fmt"
    "net/mail"
    "regexp"
)

var (
    // Validate: anchored, the whole string must be an address-shaped token.
    emailShape = regexp.MustCompile(`^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$`)
    // Extract: unanchored, \b keeps it from starting or ending mid-word.
    emailFind = regexp.MustCompile(`\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b`)
)

func looksLikeEmail(s string) bool { return emailShape.MatchString(s) }

// parsesAsAddress uses net/mail (an RFC 5322 address parser). It also accepts
// "a@b" and "Name <a@b.com>", so compare the parsed Address with the input.
func parsesAsAddress(s string) bool {
    a, err := mail.ParseAddress(s)
    return err == nil && a.Address == s
}

func demo() {
    cases := []string{"a@b.co", "a@b", "a..b@x.com", "Name <a@b.com>", "junk a@b.co junk", "a@b.com\n"}
    for _, s := range cases {
        fmt.Printf("%-18q shape=%-5v net/mail=%-5v unanchored=%v\n",
            s, looksLikeEmail(s), parsesAsAddress(s), emailFind.MatchString(s))
    }
    fmt.Printf("%q\n", emailFind.FindAllString("Contact dev@birdor.com or support@example.org.", -1))
}

Accept/reject corpus for the anchored email shape (6 accepted, 10 rejected) and the unanchored extraction form (5 and 5). Expected output: `email shape (anchored) 6/10 ok`, `email, unanchored (extraction form) 5/5 ok`. Python 3.13 differs only on the trailing-newline input.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const checks = [
  {
    name: "email shape (anchored)",
    re: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/,
    yes: ["a@b.co", "first.last+tag@example.com", "user_1@sub.example.org", "x@a-b.io", "UPPER@EXAMPLE.COM", "a..b@x.com"],
    no: ["plain", "@no.local", "a@b", "a@@b.com", "a b@c.com", "a@b.c", "a@b.com\n", "\"q u\"@x.com", "a@b.com.", "me@例え.jp"],
  },
  {
    name: "email, unanchored (extraction form)",
    re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/,
    yes: ["a@b.co", "dev@birdor.com", "write to x@y.org now", "<a@b.io>", "not: ok a@b.co ::: junk"],
    no: ["plain", "@no.local", "a@b", "a@@b", "a b"],
  },
];

for (const { name, re, yes, no } of checks) {
  const bad = [...yes.filter(s => !re.test(s)), ...no.filter(s => re.test(s))];
  console.log(name, yes.length + "/" + no.length, bad.length === 0 ? "ok" : bad);
}

In practice

  • Go net/mail — `mail.ParseAddress` parses RFC 5322 style addresses. Observed on Go 1.24: it accepts `a@b`, `Name <a@b.com>` and the quoted `"q u"@x.com`, and rejects `a..b@x.com`, `a@@b.com` and `a b@c.com`.
  • HTML Standard (input type=email) — The specification defines a deliberately simplified pattern for valid email addresses and calls it a willful violation of RFC 5322, a precedent for treating email checks as a shape policy (per the HTML Standard; not run here).
  • GNU grep — `grep -oE` is the extraction mode: it prints each match on its own line, with no anchors. Observed with grep 3.11 on a sentence containing two addresses.
  • Python re — `re.search` with `$` accepts a trailing newline, `re.fullmatch` does not, and `\d` matches fullwidth digits for `str` patterns (observed on Python 3.13); the validation idiom differs from Go and JavaScript.

Trade-offs

Pros

  • Cheap, dependency-free and linear time on RE2; the same pattern works in a form hint, a log pipeline and a WAF rule where code cannot run.
  • A named, tested shape documents the policy that is actually enforced.
  • Anchored validators fail closed: no match, no pass.

Cons

  • Never proves existence or deliverability; that needs a parser, a checksum or a confirmation round trip.
  • Policy shows up as errors in both directions: valid inputs rejected (quoted local parts, IDN) and odd ones accepted (`a..b@x.com`).
  • `$` and `\d` behave differently across engines, so a pattern that is a validator in Go can be a leaky one in Python.

IPv4 octets must stay in 0-255 (not `\d{1,3}`), IPv6 and URLs are better parsed with `net/netip` and `net/url` than matched, and hostnames need label-length rules a regex only half expresses.

The problem

Network strings look regular, so people write `(\d{1,3}\.){3}\d{1,3}` for IPv4 and call it done, which accepts `999.999.999.999`. The patterns that are worth keeping check the part a regex can check (octet range, label length, scheme) and hand the rest to `net/netip` and `net/url`, which also cover IPv6 zones, prefixes and escaping that no readable regex gets right.

How it works

  • IPv4 octet: `(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)` covers 0-255 and rejects leading zeros; the address is one octet plus `(?:\.octet){3}`. Observed on Go 1.24 and Node 22 (identical): accepts 6 of 6 (`0.0.0.0`, `127.0.0.1`, `192.168.1.1`, `255.255.255.255`, `10.0.0.254`, `8.8.8.8`), rejects 9 of 9 (`256.1.1.1`, `1.2.3`, `1.2.3.4.5`, `01.2.3.4`, `1.2.3.-4`, `999.999.999.999`, `a.b.c.d`, a trailing newline, a leading space). `netip.ParseAddr` agrees: `01.2.3.4` fails with `IPv4 field has octet with leading zero`, `256.1.1.1` with `IPv4 field has value >255`.
  • The Regex Snippets tool's `ipv4` pattern uses the same range-checked octets (0-255, no leading zeros) and, because it runs in JavaScript, adds the neighbour guards `(?<!\d|\d\.)` and `(?!\d|\.\d)`, so `999.999.999.999`, `256.1.1.1`, `01.2.3.4` and `1.2.3.4.5` yield nothing. This entry's anchored form is the Go/RE2-compatible equivalent of the octet part.
  • Extracting IPs: dropping the anchors and adding `\b` finds both addresses in `gw 10.0.0.1, dns 8.8.8.8` and nothing in `999.999.999.999`, but `1.2.3.4.5` still yields `1.2.3.4` and `[::ffff:10.0.0.1]` yields `10.0.0.1` (12 inputs, same on Go and Node; GNU grep -P agrees on `1.2.3.4.5`). `\b` treats `.` as a boundary and RE2 has no lookaround to forbid a neighbouring dot or digit; extract loose candidates and confirm each with `netip.ParseAddr` when that matters.
  • CIDR: IPv4 address plus `/(?:3[0-2]|[12]?\d)`. Accepts 6 of 6 (`10.0.0.0/8`, `192.168.0.0/16`, `0.0.0.0/0`, `172.16.0.0/12`, `203.0.113.7/32`, `10.1.2.3/24`), rejects 7 of 7 (`/33`, empty prefix, no prefix, `/-1`, `256.0.0.0/8`, `/08x`, three octets). The regex cannot see host bits: `netip.ParsePrefix("10.0.0.1/8")` succeeds and `Masked()` gives `10.0.0.0/8`. Whether host bits must be zero is policy; test `p == p.Masked()`.
  • IPv6 is a parsing job. In JavaScript the tool's IPv6 pattern now finds `::1`, `::`, `2001:db8::` and `1:2:3:4:5:6:7::` and rejects `1::2::3` and `::ffff:192.0.2.1` as whole addresses, but it ignores zones and embedded-IPv4 tails. Use `netip.ParseAddr` (also handles zones such as `fe80::1%eth0` and gives `Is4()`, `Is6()`, `Unmap()`) and keep a regex only for locating candidates in text.
  • Hostnames: a label is `[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?` (1-63 characters, no leading or trailing hyphen), repeated with dots, ending in an alphabetic TLD `[A-Za-z]{2,}`. Accepts 7 of 7 (including a 63-character label and `xn--bcher-kva.example`), rejects 11 of 11 (including a 64-character label, `exa_mple.com`, `example..com`, `example.c`, a trailing dot, `localhost`). The 253-character total cannot be expressed; check `len(s)` in code. The TLD rule rejects single-label names and punycode TLDs such as `example.xn--p1ai` (observed); relax it if those must pass.
  • URL shape: `^https?://[^\s/$.?#].[^\s]*$` with the `i` flag (the tool's body, anchored) accepts 5 of 5 and rejects 7 of 7 (`ftp://…`, bare domain, `http://`, a space after the scheme, scheme-relative `//…`, `http:///x`, `mailto:…`). It cannot judge validity: Go's `url.Parse` accepts `not a url` (as a relative path), `http://` (empty host) and `https://example.com:99999` (port unchecked), and fails on `https://exa mple.com` with `invalid character " " in host name`. Check `Scheme` and `Hostname()` after parsing.
  • Extracting URLs from prose: the tool's `\bhttps?:\/\/[^\s/$.?#].[^\s]*` keeps trailing punctuation (`see https://birdor.com/docs.` gives `https://birdor.com/docs.`; `<https://x.io/a>, then` gives `https://x.io/a>,`). The snippet matches `\bhttps?://[^\s<>"']+` and trims trailing `.,;:!?'"` and a `)` only when unbalanced, so `Foo_(bar)` keeps its parenthesis and `(https://example.com/a)` loses the outer one. 5 matching and 7 non-matching inputs, same on Go and Node.

Examples

Go
import (
    "fmt"
    "net/netip"
    "net/url"
    "regexp"
    "strings"
)

const octet = `(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)`

var (
    ipv4Shape     = regexp.MustCompile(`^` + octet + `(?:\.` + octet + `){3}$`)
    cidr4Shape    = regexp.MustCompile(`^` + octet + `(?:\.` + octet + `){3}/(?:3[0-2]|[12]?\d)$`)
    hostnameShape = regexp.MustCompile(`^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$`)
    rawURL        = regexp.MustCompile(`(?i)\bhttps?://[^\s<>"']+`)
)

// isHostname adds the one rule a regex cannot express: 253 characters in total.
func isHostname(s string) bool { return len(s) <= 253 && hostnameShape.MatchString(s) }

// isIP and isCIDR parse instead of matching: they cover IPv6 and reject the
// same bad IPv4 inputs the regex does (octet > 255, leading zeros, wrong length).
func isIP(s string) bool {
    _, err := netip.ParseAddr(s)
    return err == nil
}

func isCIDR(s string) bool {
    _, err := netip.ParsePrefix(s)
    return err == nil
}

// isHTTPURL: url.Parse accepts "not a url" as a relative path, so check the
// scheme and host explicitly.
func isHTTPURL(s string) bool {
    u, err := url.Parse(s)
    return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Hostname() != ""
}

// trimURL drops trailing punctuation and an unbalanced ")" from a raw URL match.
func trimURL(u string) string {
    for len(u) > 0 {
        last := u[len(u)-1]
        switch {
        case strings.IndexByte(".,;:!?'\"", last) >= 0:
        case last == ')' && strings.Count(u, ")") > strings.Count(u, "("):
        default:
            return u
        }
        u = u[:len(u)-1]
    }
    return u
}

func demo() {
    for _, s := range []string{"192.168.1.1", "256.1.1.1", "01.2.3.4", "::1", "2001:db8::", "1::2::3"} {
        fmt.Printf("%-12s regex=%-5v netip=%v\n", s, ipv4Shape.MatchString(s), isIP(s))
    }
    fmt.Println(cidr4Shape.MatchString("10.0.0.0/33"), isCIDR("10.0.0.0/33"), isCIDR("2001:db8::/32"))
    fmt.Println(isHostname("sub.example.co.uk"), isHostname("exa_mple.com"), isHostname("localhost"))
    fmt.Println(isHTTPURL("https://example.com/a?b=c"), isHTTPURL("not a url"), isHTTPURL("http:///x"), isHTTPURL("mailto:a@b.co"))
    for _, s := range []string{"see https://birdor.com/docs.", "(https://example.com/a)", "wiki https://en.wikipedia.org/wiki/Foo_(bar) end"} {
        fmt.Println(trimURL(rawURL.FindString(s)))
    }
}

Accept/reject corpus for the IPv4, CIDR, hostname and URL-shape patterns (counts printed as accepted/rejected: 6/9, 6/7, 7/11, 5/7). The hostname corpus includes 63- and 64-character labels.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const checks = [
  {
    name: "ipv4",
    re: /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/,
    yes: ["0.0.0.0", "127.0.0.1", "192.168.1.1", "255.255.255.255", "10.0.0.254", "8.8.8.8"],
    no: ["256.1.1.1", "1.2.3", "1.2.3.4.5", "01.2.3.4", "1.2.3.-4", "999.999.999.999", "a.b.c.d", "1.2.3.4\n", " 1.2.3.4"],
  },
  {
    name: "cidr4",
    re: /^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}\/(?:3[0-2]|[12]?\d)$/,
    yes: ["10.0.0.0/8", "192.168.0.0/16", "0.0.0.0/0", "172.16.0.0/12", "203.0.113.7/32", "10.1.2.3/24"],
    no: ["10.0.0.0/33", "10.0.0.0/", "10.0.0.0", "10.0.0.0/-1", "256.0.0.0/8", "10.0.0.0/08x", "10.0.0/8"],
  },
  {
    name: "hostname",
    re: /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}$/,
    yes: ["example.com", "sub.example.co.uk", "a-b.example.org", "xn--bcher-kva.example", "x1.io", "localhost.localdomain", "a".repeat(63) + ".com"],
    no: ["localhost", "-bad.example.com", "bad-.example.com", "exa_mple.com", "example..com", "example.c", "example.com.", "http://example.com", "exa mple.com", ".example.com", "a".repeat(64) + ".com"],
  },
  {
    name: "http(s) URL",
    re: /^https?:\/\/[^\s\/$.?#].[^\s]*$/i,
    yes: ["http://example.com", "https://example.com/a/b?c=d#e", "HTTPS://EXAMPLE.COM", "https://a.b:8080/x", "http://127.0.0.1/"],
    no: ["ftp://example.com", "example.com", "http://", "https:// example.com", "//example.com", "http:///x", "mailto:a@b.co"],
  },
];

for (const { name, re, yes, no } of checks) {
  const bad = [...yes.filter(s => !re.test(s)), ...no.filter(s => re.test(s))];
  console.log(name, yes.length + "/" + no.length, bad.length === 0 ? "ok" : bad);
}

Extraction corpus: each case lists the input and the matches expected, including the `1.2.3.4.5` leak and the unbalanced trailing punctuation that the Go `trimURL` removes afterwards. Expected output: `url-extract 12 ok`, `ipv4-extract 12 ok`.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const finders = [
  {
    name: "url-extract",
    re: /\bhttps?:\/\/[^\s<>"']+/ig,
    pick: m => m[0],
    cases: [
      ["see https://birdor.com/docs.", ["https://birdor.com/docs."]],
      ["(https://example.com/a)", ["https://example.com/a)"]],
      ["<https://x.io/a>, then more", ["https://x.io/a"]],
      ["http://a.b/c?d=e;", ["http://a.b/c?d=e;"]],
      ["no url", []],
      ["wiki https://en.wikipedia.org/wiki/Foo_(bar) end", ["https://en.wikipedia.org/wiki/Foo_(bar)"]],
      ["ftp://x.io/a", []],
      ["example.com/a", []],
      ["http:/x.io", []],
      ["htp://x.io", []],
      ["https://", []],
      ["https:// x.io", []],
    ],
  },
  {
    name: "ipv4-extract",
    re: /\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b/g,
    pick: m => m[0],
    cases: [
      ["gw 10.0.0.1, dns 8.8.8.8", ["10.0.0.1","8.8.8.8"]],
      ["ip=192.168.1.1;", ["192.168.1.1"]],
      ["[::ffff:10.0.0.1]", ["10.0.0.1"]],
      ["255.255.255.255", ["255.255.255.255"]],
      ["0.0.0.0/0", ["0.0.0.0"]],
      ["256.1.1.1 and 1.1.1.1", ["1.1.1.1"]],
      ["999.999.999.999", []],
      ["1.2.3", []],
      ["no address", []],
      ["1.2.3.4.5", ["1.2.3.4"]],
      ["v1.2.3.4-rc", []],
      ["01.2.3.4", []],
    ],
  },
];

for (const { name, re, pick, cases } of finders) {
  const bad = cases.filter(([s, want]) => {
    const got = [...s.matchAll(re)].map(pick).filter(x => x !== null);
    return JSON.stringify(got) !== JSON.stringify(want);
  });
  console.log(name, cases.length, bad.length === 0 ? "ok" : bad);
}

In practice

  • Go net/netip — `ParseAddr` and `ParsePrefix` reject out-of-range octets, leading zeros and bad prefix lengths (`prefix length out of range` for `10.0.0.0/33`), and accept IPv6 forms including `::` and zones (observed on Go 1.24).
  • Go net/url — `url.Parse` is lenient by design: relative paths, empty hosts and unchecked ports pass, so callers check `Scheme` and `Hostname()` themselves (observed on Go 1.24); `ParseRequestURI` additionally rejects `not a url`.
  • GNU grep — `grep -oP` with the extraction octet pattern prints `1.2.3.4` for the input `x 1.2.3.4.5 y`, the same boundary leak seen on Go and Node (grep 3.11).

Trade-offs

Pros

  • The octet, CIDR and hostname patterns use only constructs common to RE2, JavaScript and PCRE, so they fit configs, WAF rules and log pipelines.
  • net/netip and net/url give correct IPv6, prefix and escaping handling without a regex that nobody can review.
  • Range-checked octets remove a whole class of silent false accepts.

Cons

  • A regex cannot enforce host bits, port ranges, the 253-character hostname limit or percent-encoding rules.
  • Extraction cannot forbid a neighbouring dot or digit without lookaround (`1.2.3.4.5` still yields `1.2.3.4` on RE2).
  • Hostname TLD rules are policy: single-label and punycode TLDs fail the shape pattern.

UUID versions, the official semver.org pattern (named groups, RE2-compatible, not valid in JavaScript as written), 3/4/6/8-digit hex colors, ISO dates that a regex cannot check against the calendar, and CSS lengths.

The problem

Identifiers have a fixed layout, which makes them look ideal for regexes, and mostly they are: UUIDs, semantic versions and hex colors are exactly the kind of flat shape a pattern states well. The traps are at the edges: the version and variant nibbles of a UUID, the official semver pattern's named-group syntax (valid on RE2 and Python, invalid on V8 as written), colors that CSS writes with 4 or 8 digits, and dates whose month lengths and leap years are calendar facts a regex cannot know.

How it works

  • UUID shape is 8-4-4-4-12 hex digits. The version-neutral pattern accepts 5 of 5 (a v4 sample, the nil UUID, the max UUID, uppercase, a v7 sample) and rejects 6 of 6 (no hyphens, 31 and 33 hex digits, a `g`, a truncated value, braces). The v4 pattern adds `4` as the first digit of group 3 and `[89abAB]` as the first digit of group 4: it accepts 5 of 5 and rejects 6 of 6, including the v1 and v7 samples and a value with variant `c`. Both results are identical on Go 1.24 and Node 22. The v4 body equals the Regex Snippets tool's `uuid-v4`, anchored instead of wrapped in `\b`; use the version-neutral form to accept other versions.
  • semver: the semver.org page publishes one regex with named groups (`(?P<major>…)`, `prerelease`, `buildmetadata`). Observed on Go 1.24 it compiles unchanged, and `FindStringSubmatch` plus `SubexpNames` return major 1, minor 0, patch 0, prerelease `rc.1`, buildmetadata `build.5` for `1.0.0-rc.1+build.5`. Python 3.13 accepts the same text. Node 22 rejects it: `Invalid regular expression: /^(?P<major>0|[1-9]\d*)$/: Invalid group`; write `(?<major>…)` (accepted, groups object populated) or use the numbered-group JavaScript variant, which is what the snippet uses.
  • semver corpus (identical on Go and Node): accepts 8 of 8 (`0.0.4`, `1.2.3`, `10.20.30`, `1.1.2-prerelease+meta`, `1.0.0-alpha.1`, `1.0.0-0.3.7`, `1.0.0+20130313144700`, `1.0.0-x-y-z.--`) and rejects 11 of 11 (`1`, `1.2`, `1.2.3.4`, `01.1.1`, `1.01.1`, `1.1.01`, `1.2.3-`, `1.2.3-01`, `v1.2.3`, `1.2.3+`, `1.2.3-+`). A leading `v` is not part of semver; strip it first when tags are written `v1.2.3`.
  • Hex colors: `^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$` accepts 6 of 6 (`#fff`, `#FFF`, `#1a2b3c`, `#1a2b3c80`, `#abcd`, `#000000`) and rejects 8 of 8 (`fff`, `#ff`, `#fffff`, `#fffffff`, `#ggg`, `#12345g`, `# fff`, a trailing newline). The tool's `#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})\b` also covers the 4- and 8-digit CSS Color 4 forms (`#abcd`, `#abcdef80`); this entry anchors instead of using `\b`.
  • Dates: `^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$` (the tool's ranges, anchored) accepts `2026-09-14`, `2000-01-01`, `1999-12-31`, `2024-02-29` and also `2026-02-30` and `2026-04-31`, because month lengths are not expressible; it rejects 9 of 9 (month 13, month 00, day 00, day 32, two-digit year, slashes, unpadded, a time suffix, a trailing newline). A leap year needs arithmetic (divisible by 4, except centuries not divisible by 400), so a second step is required: observed on Go 1.24, `time.Parse("2006-01-02", …)` fails `2026-02-30` and `2023-02-29` with `day out of range`, `2026-13-01` with `month out of range`, accepts `2024-02-29`, and fails `2026-9-14` with `cannot parse "9-14" as "01"`.
  • CSS length: `^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|r?em|ch|ex|vh|vw|vmin|vmax|pt|pc|cm|mm|in|%)$` accepts 7 of 7 (`16px`, `1.5rem`, `-0.5em`, `.5em`, `100%`, `2.25in`, `+3vh`) and rejects 8 of 8 (unitless `16`, `px`, `1.5.5rem`, `16 px`, `16PX`, `1e3px`, `16pxx`, `--1px`). The unit list is a subset (no `dvh`, `svh`, container units); CSS unit names are case-insensitive per the CSS specs (not run here), so add the `i` flag if `16PX` must pass; unitless `0` is legal CSS and excluded here.
  • Anchors again: on Python 3.13 every pattern in this entry that ends in `$` (UUID, semver, hex color, CSS length; the ISO date too) also accepts a trailing newline, as the email and IPv4 patterns do; use `re.fullmatch` there.

Examples

Go
import (
    "fmt"
    "regexp"
    "time"
)

var (
    // The official semver.org pattern (named groups) compiles unchanged on RE2.
    semverRe = regexp.MustCompile(`^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)` +
        `(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?` +
        `(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`)
    uuidV4Re  = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$`)
    dateShape = regexp.MustCompile(`^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$`)
)

// semverParts returns the named groups, or nil when s is not a semantic version.
func semverParts(s string) map[string]string {
    m := semverRe.FindStringSubmatch(s)
    if m == nil {
        return nil
    }
    parts := map[string]string{}
    for i, name := range semverRe.SubexpNames() {
        if name != "" {
            parts[name] = m[i]
        }
    }
    return parts
}

// validDate: the regex checks shape and month/day ranges, time.Parse checks
// the calendar (days per month, leap years).
func validDate(s string) bool {
    if !dateShape.MatchString(s) {
        return false
    }
    _, err := time.Parse("2006-01-02", s)
    return err == nil
}

func demo() {
    fmt.Println(semverParts("1.0.0-rc.1+build.5"))
    fmt.Println(semverParts("01.2.3") == nil, semverParts("v1.2.3") == nil)
    fmt.Println(uuidV4Re.MatchString("9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"), uuidV4Re.MatchString("018f4c2e-7b1a-7c3d-8e2f-123456789abc"))
    for _, s := range []string{"2024-02-29", "2026-02-30", "2023-02-29", "2026-04-31", "2026-13-01"} {
        fmt.Printf("%s shape=%-5v valid=%v\n", s, dateShape.MatchString(s), validDate(s))
    }
}

Accept/reject corpus for the six identifier patterns (accepted/rejected: 5/6, 5/6, 8/11, 6/8, 6/9, 7/8). The ISO-date accepted list deliberately contains `2026-02-30` and `2026-04-31`: the shape passes, the calendar does not. The semver regex is the numbered-group JavaScript form from semver.org.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const checks = [
  {
    name: "uuid",
    re: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,
    yes: ["9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", "00000000-0000-0000-0000-000000000000", "ffffffff-ffff-ffff-ffff-ffffffffffff", "550E8400-E29B-41D4-A716-446655440000", "018f4c2e-7b1a-7c3d-8e2f-123456789abc"],
    no: ["9b1deb4d3b7d4bad9bdd2b0d7b3dcb6d", "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6", "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6dd", "g b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", "9b1deb4d-3b7d-4bad-9bdd", "{9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d}"],
  },
  {
    name: "uuid v4",
    re: /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/,
    yes: ["9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d", "f47ac10b-58cc-4372-a567-0e02b2c3d479", "A987FBC9-4BED-4078-8F07-9141BA07C9F3", "123e4567-e89b-42d3-a456-426614174000", "00000000-0000-4000-8000-000000000000"],
    no: ["550e8400-e29b-11d4-a716-446655440000", "018f4c2e-7b1a-7c3d-8e2f-123456789abc", "9b1deb4d-3b7d-4bad-cbdd-2b0d7b3dcb6d", "9b1deb4d3b7d4bad9bdd2b0d7b3dcb6d", "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6", "not-a-uuid"],
  },
  {
    name: "semver (numbered groups)",
    re: /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,
    yes: ["0.0.4", "1.2.3", "10.20.30", "1.1.2-prerelease+meta", "1.0.0-alpha.1", "1.0.0-0.3.7", "1.0.0+20130313144700", "1.0.0-x-y-z.--"],
    no: ["1", "1.2", "1.2.3.4", "01.1.1", "1.01.1", "1.1.01", "1.2.3-", "1.2.3-01", "v1.2.3", "1.2.3+", "1.2.3-+"],
  },
  {
    name: "hex color",
    re: /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,
    yes: ["#fff", "#FFF", "#1a2b3c", "#1a2b3c80", "#abcd", "#000000"],
    no: ["fff", "#ff", "#fffff", "#fffffff", "#ggg", "#12345g", "# fff", "#fff\n"],
  },
  {
    name: "iso date (shape only)",
    re: /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/,
    yes: ["2026-09-14", "2000-01-01", "1999-12-31", "2024-02-29", "2026-02-30", "2026-04-31"],
    no: ["2026-13-01", "2026-00-10", "2026-01-00", "2026-01-32", "26-01-01", "2026/01/01", "2026-1-1", "2026-01-01T00:00", "2026-01-01\n"],
  },
  {
    name: "css length",
    re: /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:px|r?em|ch|ex|vh|vw|vmin|vmax|pt|pc|cm|mm|in|%)$/,
    yes: ["16px", "1.5rem", "-0.5em", ".5em", "100%", "2.25in", "+3vh"],
    no: ["16", "px", "1.5.5rem", "16 px", "16PX", "1e3px", "16pxx", "--1px"],
  },
];

for (const { name, re, yes, no } of checks) {
  const bad = [...yes.filter(s => !re.test(s)), ...no.filter(s => re.test(s))];
  console.log(name, yes.length + "/" + no.length, bad.length === 0 ? "ok" : bad);
}

In practice

  • semver.org — The specification site publishes the reference regular expression (a named-group form and a numbered-group form for JavaScript). The named form was run unchanged on Go 1.24 and Python 3.13 and failed on Node 22 as described above.
  • Go time — `time.Parse` is the calendar check a date regex cannot be: it knows month lengths and leap years (observed on Go 1.24 for 2024-02-29 vs 2023-02-29).
  • golang.org/x/mod/semver — Go's module tooling compares versions with a package that requires the leading `v` (per its documentation; not run here), the opposite of the semver.org pattern, which rejects `v1.2.3`.

Trade-offs

Pros

  • Flat fixed-layout identifiers are where regexes are most reliable and fastest to review.
  • The official semver pattern is a vetted reference and RE2-compatible, so Go can use it unchanged.
  • Splitting shape (regex) from calendar (time.Parse) keeps each half small and testable.

Cons

  • Named-group syntax differs (the official semver text fails on V8 as written), so a shared pattern needs a per-engine form.
  • The regex alone accepts impossible dates (`2026-02-30`); calendar facts are always a second step.
  • Version-specific UUID, color-notation and unit lists are policies that age: new UUID versions, CSS units and color syntaxes need pattern edits.

China mobile numbers, the 18-digit resident ID (shape in a regex, check digit and birth date in code), E.164, card numbers (Luhn in code) and postcodes: what the pattern proves and what needs a second step.

The problem

Locale-specific numbers (mobile numbers, resident IDs, card numbers, postcodes) have a recognisable shape, so a regex is the first thing people reach for, and it is also where "valid" gets confused with "well-formed". A pattern proves the digits are arranged correctly. It cannot compute a check digit, know that `02-30` is not a date, or know that a number was ever issued. The reliable design is two steps: a regex for shape, then plain code for the arithmetic.

How it works

  • China mainland mobile: `^1[3-9]\d{9}$` (the tool's `phone-cn-mobile` body, anchored). Observed on Go 1.24 and Node 22 (identical): accepts 5 of 5 (`13812345678`, `15000000000`, `19999999999`, `14500000000`, `17012345678`), rejects 7 of 7 (`12812345678`, 10 digits, 12 digits, `23812345678`, `+8613812345678`, `138 1234 5678`, a trailing newline). It checks the leading digits and length only, not that a segment is allocated; strip `+86` and spaces before matching.
  • Extraction trap with `\b`: the tool's `\b1[3-9]\d{9}\b` finds the number in `手机13812345678已验证` on Go and Node, because CJK characters are not word characters for an ASCII `\b`, but finds nothing on Python 3.13 for a `str` pattern, where Unicode `\w` treats them as word characters (`re.A` restores the Go/JS behaviour). It correctly skips `213812345678` and the 12- and 16-digit runs.
  • E.164: `^\+[1-9]\d{6,14}$` (the tool's pattern, anchored) accepts 5 of 5 (`+14155552671`, `+442071838750`, `+8613812345678`, `+1234567`, a 15-digit number) and rejects 7 of 7 (no plus, leading `0`, 6 digits, 16 digits, spaces, a bare plus, hyphens). The 15-digit cap comes from E.164; the 7-digit floor is the tool's heuristic, not part of that limit. Whether a number is dialable depends on per-country numbering metadata (libphonenumber keeps it; per its documentation, not run here), not on a pattern.
  • Resident ID, 18 digits: 6-digit region, 8-digit birth date, 3-digit sequence, 1 check character. Shape: `^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$`. The corpus uses only synthetic numbers computed by the algorithm below with birth dates in 2096-2099, which are not issued to anyone: accepts 5 of 5 (including a February 30 and a lowercase `x`) and rejects 8 of 8 (leading `0`, 16 and 19 digits, month 13, day 32, century `21`, check character `Y`, a trailing newline). Identical on Go and Node.
  • The check character is ISO 7064 MOD 11-2: multiply the first 17 digits by the weights 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 (that is 2^(17-i) mod 11), sum, and look up the sum mod 11 in `10X98765432`. The Go sketch also parses digits 7-14 with `time.Parse("20060102", …)`. Observed on synthetic numbers: `110101209912310015`, `110101209901010025` and `110101209602290039` (a real leap day) are valid; `110101209902300040` (February 30) and `110101209902290057` (2099 is not a leap year) pass the shape but fail the date; a wrong check character fails. The weights and three check characters were recomputed independently from the 2^n mod 11 form. The region code is not verified, which needs the administrative-division table.
  • Card numbers: the tool's grouped pattern `\b(?:\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{1,7}|\d{4}[ -]?\d{6}[ -]?\d{5})\b` also accepts an Amex printed in its usual 4-6-5 grouping (`3782 822463 10005`) through its second alternative `\d{4}[ -]?\d{6}[ -]?\d{5}`. This entry normalises first (strip spaces and hyphens) and then uses `^\d{13,19}$` (accepts 6 of 6 including `4111111111111112`, which is well-shaped but fails Luhn; rejects 7 of 7: 12 digits, 20 digits, embedded spaces, letters, hyphens, an empty string, fullwidth digits). 13-19 is a practical window, not a statement about any issuer.
  • Luhn: from the rightmost digit, double every second digit (subtract 9 when the result exceeds 9), sum everything, and require the sum mod 10 to be 0. Observed on Go 1.24: `4111 1111 1111 1111` and `3782 8224 6310 005` (widely published test numbers) pass; `4111-1111-1111-1112` fails the checksum; `4111 1111` fails the length. Luhn catches most single-digit typos; it says nothing about whether the account exists.
  • Postcodes: China `^\d{6}$` accepts `200000`, `100000`, `030000`, `518000`, `835000` and rejects 5 digits, 7 digits, a letter, an inner space, leading space and the fullwidth `200000` (Go and Node; Python 3.13 accepts that last one). US `^\d{5}(?:-\d{4})?$` accepts 5 of 5 including ZIP+4 and rejects 6 of 6. Six digits alone is broad when scanning prose: the tool's `\b\d{6}\b` finds both `123456` and `654321` in `code 123456 and 654321`, so anchor it to a label or a field.

Examples

Go
import (
    "fmt"
    "regexp"
    "strings"
    "time"
)

var (
    cnMobile   = regexp.MustCompile(`^1[3-9]\d{9}$`)
    cnID18     = regexp.MustCompile(`^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$`)
    cardDigits = regexp.MustCompile(`^\d{13,19}$`)
    cardSep    = strings.NewReplacer(" ", "", "-", "")
)

// ISO 7064 MOD 11-2: weights for the first 17 digits and the check characters.
var idWeights = [17]int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}

const idCheckChars = "10X98765432"

// idCheckChar computes the 18th character from the first 17 digits.
func idCheckChar(first17 string) byte {
    sum := 0
    for i, w := range idWeights {
        sum += int(first17[i]-'0') * w
    }
    return idCheckChars[sum%11]
}

// validCNID checks shape, then the birth date, then the check character.
func validCNID(s string) bool {
    if !cnID18.MatchString(s) {
        return false
    }
    if _, err := time.Parse("20060102", s[6:14]); err != nil {
        return false
    }
    return idCheckChar(s[:17]) == byte(strings.ToUpper(s[17:])[0])
}

// luhnValid runs the Luhn checksum over a digit string.
func luhnValid(digits string) bool {
    sum, double := 0, false
    for i := len(digits) - 1; i >= 0; i-- {
        d := int(digits[i] - '0')
        if double {
            if d *= 2; d > 9 {
                d -= 9
            }
        }
        sum += d
        double = !double
    }
    return sum%10 == 0
}

// validCard strips separators first, then checks length and Luhn.
func validCard(s string) bool {
    d := cardSep.Replace(s)
    return cardDigits.MatchString(d) && luhnValid(d)
}

func demo() {
    // Synthetic ID numbers (birth dates in 2096-2099), not issued to anyone.
    for _, first17 := range []string{"11010120991231001", "11010120990101002", "11010120960229003", "11010120990230004", "11010120990229005"} {
        id := first17 + string(idCheckChar(first17))
        fmt.Printf("%s shape=%-5v valid=%v\n", id, cnID18.MatchString(id), validCNID(id))
    }
    fmt.Println(validCNID("110101209912310010"), validCNID("11010120991231001X"))
    fmt.Println(cnMobile.MatchString("13812345678"), cnMobile.MatchString("12812345678"))
    for _, s := range []string{"4111 1111 1111 1111", "3782 8224 6310 005", "4111-1111-1111-1112", "4111 1111"} {
        fmt.Printf("%-22q valid=%v\n", s, validCard(s))
    }
}

Accept/reject corpus (accepted/rejected: 5/7, 5/7, 5/8, 6/7, 5/6, 5/6). The ID numbers are synthetic, generated by the Go sketch with birth dates in 2096-2099, and one accepted value (February 30) shows that shape is not validity; `4111111111111112` passes the digit-shape check but fails Luhn. The fullwidth-digit inputs are rejected on Go and Node and accepted on Python 3.13.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const checks = [
  {
    name: "cn mobile",
    re: /^1[3-9]\d{9}$/,
    yes: ["13812345678", "15000000000", "19999999999", "14500000000", "17012345678"],
    no: ["12812345678", "1381234567", "138123456789", "23812345678", "+8613812345678", "138 1234 5678", "13812345678\n"],
  },
  {
    name: "e164",
    re: /^\+[1-9]\d{6,14}$/,
    yes: ["+14155552671", "+442071838750", "+8613812345678", "+1234567", "+123456789012345"],
    no: ["14155552671", "+0155552671", "+123456", "+1234567890123456", "+1 415 555 2671", "+", "+1-415-555-2671"],
  },
  {
    name: "cn id 18 (shape, synthetic numbers)",
    re: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/,
    yes: ["110101209912310015", "110101209901010025", "110101209602290039", "110101209902300040", "11010120991231001x"],
    no: ["010101209912310015", "1101012099123100", "1101012099123100155", "110101209913310015", "110101209912320015", "110101219912310015", "11010120991231001Y", "110101209912310015\n"],
  },
  {
    name: "card digits (shape)",
    re: /^\d{13,19}$/,
    yes: ["4111111111111111", "378282246310005", "6011111111111117", "5555555555554444", "4222222222222", "4111111111111112"],
    no: ["411111111111", "41111111111111111111", "4111 1111 1111 1111", "abcd111111111111", "4111-1111-1111-1111", "", "4111111111111111"],
  },
  {
    name: "zip cn",
    re: /^\d{6}$/,
    yes: ["200000", "100000", "030000", "518000", "835000"],
    no: ["20000", "2000000", "20000a", "200 000", "200000", " 200000"],
  },
  {
    name: "zip us",
    re: /^\d{5}(?:-\d{4})?$/,
    yes: ["94105", "94105-1234", "00501", "10001", "99950-0001"],
    no: ["9410", "941055", "94105-123", "94105-", "94105 1234", "abcde"],
  },
];

for (const { name, re, yes, no } of checks) {
  const bad = [...yes.filter(s => !re.test(s)), ...no.filter(s => re.test(s))];
  console.log(name, yes.length + "/" + no.length, bad.length === 0 ? "ok" : bad);
}

In practice

  • Go time — `time.Parse("20060102", …)` is the birth-date step for the ID sketch: it rejects 20990230 and 20990229 and accepts 20960229 (observed on Go 1.24).
  • libphonenumber — Google's phone-number library parses and validates numbers per region from a metadata table instead of one pattern (per the project documentation; not run here).
  • Python re — For `str` patterns `\b` and `\d` are Unicode-aware: a mobile number next to Chinese text is not found and fullwidth digits pass `\d` (observed on Python 3.13); `re.A` limits both to ASCII.

Trade-offs

Pros

  • A shape regex is a cheap first filter that gives users an immediate hint before any lookup or arithmetic runs.
  • Splitting shape from arithmetic keeps the regex short and puts the checksum where it can be unit-tested.
  • The same shape patterns run on Go, JavaScript and PCRE, so client and server can share them.

Cons

  • Passing the shape says nothing about being issued, allocated or owned; treating it as validation is the common bug.
  • Numbering plans change (new mobile segments, new prefixes), so hard-coded ranges age.
  • Identity and card data are sensitive: use synthetic or published test numbers in tests and logs, never real ones.

Regexes for Markdown links, fenced code blocks, front matter and HTML tag names, with the exact point where nesting, escaping or context makes a regex the wrong tool and a parser is needed.

The problem

Markdown and HTML are the favourite targets of "just a quick regex", and for a flat, well-formed subset that is fine: pull the links out of a README, strip simple tags from trusted text, read the front matter of a content file. The failures are quiet. The moment structure nests (a bracket inside link text, a fence inside a fence, a `>` inside an attribute) a regex returns a plausible wrong answer rather than an error. The useful skill is knowing the boundary and switching to a parser on the other side of it.

How it works

  • Markdown inline link: `(!?)\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)` with group 1 recording a leading `!` so images are skipped in code. RE2 has no lookbehind, and the usual substitute `(?:^|[^!])` consumes the preceding character: observed on Go 1.24, it finds only the first link in `[a](x)[b](y)`. Corpus (identical on Go and Node): 6 inputs with links (plain, in a sentence, adjacent links, a quoted title, a link followed by an image, non-ASCII text) and 7 without (`![logo](img/a.png)` is matched but skipped, `[a [b] c](u)`, `[empty]()`, `[a] (x)`, plain text, `[a](x y)`, `[ref][1]`).
  • Where links break: a parenthesis in the URL. `[wiki](https://en.wikipedia.org/wiki/Foo_(bar))` yields the URL `https://en.wikipedia.org/wiki/Foo_(bar` (observed, Go and Node). The tool's `\[([^\]]+)\]\(([^)]+)\)` has the same limit and folds a title into the URL group (`[t](u "title")` gives URL `u "title"`); the tool skips images with `(?<!!)`, while this entry's version captures the `!` as well so code can skip images (RE2 has no lookbehind) and splits the title out. Nested brackets and reference-style links need a Markdown parser.
  • Fenced code: `(?m)^```[ \t]*([\w-]*)[ \t]*\n([\s\S]*?)\n```[ \t]*$` (JavaScript flag `m`). The lazy `[\s\S]*?` spans lines without the dot-all flag and stops at the first closing fence. Observed: 5 inputs match (a `go` fence, a plain fence, two fences in one text, trailing spaces after the info string, an empty body) and 5 do not (an unclosed fence, `~~~` fences, an indented fence, CRLF line endings, an info string with attributes such as `go title=x`). Normalise line endings before matching.
  • The silent failure: a four-backtick fence containing a three-backtick one. The pattern returns the inner block (`lang=go body=x`) instead of the outer one, because matching the closing fence "at least as long as the opener" needs a backreference, which RE2 does not have (CommonMark rule, per the spec; the output is observed). No error is raised; the regex is simply the wrong tool past this point.
  • Front matter: `^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)` without the multiline flag, so `^` means the start of the text; that form is portable because JavaScript has no `\A`. Observed (identical on Go and Node): matches a basic block, CRLF, a closing fence at the end of the text, trailing spaces after the closing line and a multi-line list value; does not match a document without it, an unclosed block, an empty block (`---` then `---`), a leading heading before the fence, `----` and `--- ` with a trailing space. It captures raw YAML text; parsing it is a YAML library's job.
  • HTML opening tag name: `<([a-zA-Z][a-zA-Z0-9-]*)(?:\s[^<>]*)?/?>` matches `<p>`, `<p class="lead">`, `<br/>`, `<br />`, `<my-element data-x=1>` and `<a href='/x'>`, and skips `a < b`, `x > y`, `</p>`, `<>`, `<1abc>` and `<!-- c -->` (6 and 6, Go and Node). It breaks on a `>` inside an attribute value (`<a title="x>y">` is read as `<a title="x>`), reads `<b && c>` inside a script body as a tag, and scans comment bodies as markup. The tool's `<\/?[a-zA-Z][^>]*>` has the same limits and also returns closing tags.
  • What a parser does instead: observed with golang.org/x/net/html v0.61.0 (an external module, not part of the standard library; that release's go.mod requires Go 1.26) on `<a title="x>y">t</a><script>if (a<b) {}</script><p>one<p>two`, the element sequence is `html head body a script p p`: the attribute value is intact, the script body is text, and the implied end of the first `p` is applied. Use a parser to sanitise or transform untrusted markup; keep regexes for trusted, flat, well-formed text.
  • Balanced or nested structure is outside what a regular expression describes. PCRE adds recursion (`(?R)`) but it does not exist in RE2 or V8, so it is not portable (see the conditionals and recursion entry); in Go reach for a parser such as x/net/html or a Markdown library like goldmark instead of recursion.

Examples

Go
import (
    "fmt"
    "regexp"
)

var (
    // Group 1 captures a leading "!" so images can be skipped without lookbehind.
    mdLink      = regexp.MustCompile(`(!?)\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)`)
    fencedBlock = regexp.MustCompile("(?m)^```[ \\t]*([\\w-]*)[ \\t]*\\n([\\s\\S]*?)\\n```[ \\t]*$")
    frontMatter = regexp.MustCompile(`^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)`)
)

type link struct{ Text, URL string }

func markdownLinks(src string) []link {
    var out []link
    for _, m := range mdLink.FindAllStringSubmatch(src, -1) {
        if m[1] == "!" {
            continue // an image, not a link
        }
        out = append(out, link{m[2], m[3]})
    }
    return out
}

func demo() {
    fmt.Println(markdownLinks("See [docs](https://birdor.com/docs), ![logo](a.png) and [t](u \"title\")."))
    fmt.Println(markdownLinks("[wiki](https://en.wikipedia.org/wiki/Foo_(bar))"))
    for _, m := range fencedBlock.FindAllStringSubmatch("x\n```go\nfmt.Println(1)\n```\ny\n```\nplain\n```", -1) {
        fmt.Printf("lang=%q body=%q\n", m[1], m[2])
    }
    fmt.Printf("%q\n", frontMatter.FindStringSubmatch("---\ntitle: A\n---\n# H")[1])
}

Corpus with the expected result for every input, including the known boundary cases: the parenthesised wiki URL is truncated, the four-backtick fence returns the inner block, and `<a title="x>y">` is cut at the first `>`. Expected output: `md-link (images skipped) 14 ok`, `fenced code 11 ok`, `front matter 11 ok`, `html tag name 14 ok`.

javascript
// Node 22. Go 1.24 (RE2) gives the same accept/reject result for every input.
const finders = [
  {
    name: "md-link (images skipped)",
    re: /(!?)\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g,
    pick: m => (m[1] ? null : [m[2], m[3]]),
    cases: [
      ["[a](x)", [["a","x"]]],
      ["See [docs](https://birdor.com/docs) now.", [["docs","https://birdor.com/docs"]]],
      ["[a](x)[b](y)", [["a","x"],["b","y"]]],
      ["[t](u \"title\")", [["t","u"]]],
      ["[a](x)![b](y)", [["a","x"]]],
      ["[ünï](https://example.jp/a)", [["ünï","https://example.jp/a"]]],
      ["![logo](img/a.png)", []],
      ["[a [b] c](u)", []],
      ["[empty]()", []],
      ["[a] (x)", []],
      ["plain text", []],
      ["[a](x y)", []],
      ["[ref][1]", []],
      ["[wiki](https://en.wikipedia.org/wiki/Foo_(bar))", [["wiki","https://en.wikipedia.org/wiki/Foo_(bar"]]],
    ],
  },
  {
    name: "fenced code",
    re: /^```[ \t]*([\w-]*)[ \t]*\n([\s\S]*?)\n```[ \t]*$/mg,
    pick: m => [m[1], m[2]],
    cases: [
      ["text\n```go\nfmt.Println(1)\n```\nmore", [["go","fmt.Println(1)"]]],
      ["```\nplain\n```", [["","plain"]]],
      ["```js\na\n```\nx\n```py\nb\n```", [["js","a"],["py","b"]]],
      ["```go  \nspaced\n```", [["go","spaced"]]],
      ["```\n\n```", [["",""]]],
      ["```go\nunclosed\n", []],
      ["~~~\ntilde\n~~~", []],
      ["  ```go\nindented\n  ```", []],
      ["```go\r\nx\r\n```", []],
      ["```go title=x\nattrs\n```", []],
      ["````md\n```go\nx\n```\n````", [["go","x"]]],
    ],
  },
  {
    name: "front matter",
    re: /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/g,
    pick: m => m[1],
    cases: [
      ["---\ntitle: A\ntags: [x]\n---\nbody", ["title: A\ntags: [x]"]],
      ["---\r\ntitle: A\r\n---\r\nbody", ["title: A"]],
      ["---\na: 1\n---", ["a: 1"]],
      ["---\na: 1\n---  \nbody", ["a: 1"]],
      ["---\ntitle: A\nlist:\n  - x\n  - y\n---\n# H", ["title: A\nlist:\n  - x\n  - y"]],
      ["no front matter\n---\nx\n---\n", []],
      ["---\ntitle: A\nbody without close", []],
      ["---\n---\nempty", []],
      ["# h\n---\na: 1\n---\n", []],
      ["----\na: 1\n----\n", []],
      ["--- \na: 1\n---\n", []],
    ],
  },
  {
    name: "html tag name",
    re: /<([a-zA-Z][a-zA-Z0-9-]*)(?:\s[^<>]*)?\/?>/g,
    pick: m => m[1],
    cases: [
      ["<p>", ["p"]],
      ["<p class=\"lead\">Hello", ["p"]],
      ["<br/>", ["br"]],
      ["<br />", ["br"]],
      ["<my-element data-x=1>", ["my-element"]],
      ["<a href='/x'>", ["a"]],
      ["a < b", []],
      ["x > y", []],
      ["</p>", []],
      ["<>", []],
      ["<1abc>", []],
      ["<!-- c -->", []],
      ["<a title=\"x>y\">t</a>", ["a"]],
      ["<script>if (a<b && c>d) {}</script>", ["script","b"]],
    ],
  },
];

for (const { name, re, pick, cases } of finders) {
  const bad = cases.filter(([s, want]) => {
    const got = [...s.matchAll(re)].map(pick).filter(x => x !== null);
    return JSON.stringify(got) !== JSON.stringify(want);
  });
  console.log(name, cases.length, bad.length === 0 ? "ok" : bad);
}

In practice

  • golang.org/x/net/html — HTML5 tokenizer and parser; handles quoted attributes, script bodies and implied end tags where the tag regex does not (observed with v0.61.0, which needs a recent Go toolchain).
  • goldmark — CommonMark-compliant Markdown parser for Go, used by Hugo (per the Hugo documentation, which names Goldmark as its default renderer; not run here); the right tool once links or fences nest.
  • Jekyll — Treats a file as having front matter when it starts with a line of three dashes and ends it with another such line (per the Jekyll documentation; not run here), the same delimiter shape as the pattern above.
  • Go regexp — The patterns above compile and behave identically on Go 1.24 RE2 and Node 22 for the whole corpus; the only constructs used are lazy quantifiers, `[\s\S]`, anchors and the `m` flag.

Trade-offs

Pros

  • Fine for flat, line-oriented, well-formed subsets: README links, simple tag stripping in trusted text, front matter in content files.
  • RE2 keeps these patterns linear-time, so a hostile document cannot make them blow up.
  • A regex is a few lines and needs no dependency in a script, a grep pipeline or a build step.

Cons

  • Nesting, escaping and context (code spans, comments, script bodies) produce plausible wrong answers, not errors.
  • Anything that must be right on untrusted input (sanitising HTML, rendering Markdown) belongs to a parser; a regex is not a security boundary.
  • Line endings, indentation and info-string variants multiply the cases: each fix adds a corpus entry to keep.

Debugging & troubleshooting

How `^(a+)+$` turns 30 characters into a hang on backtracking engines: the red flags (nested quantifiers, overlapping alternation, `(.*)*`), the measured growth on Python, Node, Go and grep, and the fixes in order of preference: remove the ambiguity, atomic or possessive, a linear engine, limits and timeouts.

The problem

A regex that passes every unit test can still freeze a server: `^(a+)+$` answers instantly on `aaaaaaaaab` and effectively never on 40 `a` followed by `b`. Backtracking engines (Python `re`, V8, PCRE2) try one way of splitting the input and undo the work when the rest of the pattern fails; if the pattern can split the same text many ways, a failing input forces them to try every way. On a single-threaded runtime one such call blocks all other requests (Node's event loop), and because the pattern or the input often comes from a user, the bug is a denial-of-service vulnerability (ReDoS), not just a slow query.

How it works

  • Mechanism: `(a+)+` can cut `n` letters into runs in 2^(n-1) ways. A successful match accepts the first cut, so valid inputs are fast. A failing tail (`^(a+)+$` on `a` repeated n times plus `b`) makes the engine undo and retry every cut before it reports no match. That asymmetry is why unit tests with good inputs never notice it: the test that exposes it is a near miss, a valid prefix with one wrong last character.
  • Measured growth, `^(a+)+$` on `a` repeated n times plus `b`, time ratio against the row two characters shorter (best of 3, trend only; the growth snippets print this): Python 3.13.16, n = 18..28: x3.9, x4.1, x3.9, x4.1, x4.2, x4.3. Node 22.22.0, n = 18..30: x3.8, x4.1, x4.0, x4.3, x4.5, x3.7, x3.9. Single runs at small n scattered between x2.6 and x5.8. About x4 per two characters is about x2 per character, so ten more characters cost roughly a thousand times more. The x4-per-two-characters and doubling-per-character figures quoted on the engines, quantifier and Go performance entries are the same measurement.
  • Contrast, Go 1.24.7: the same pattern on `a` repeated 100,000, 200,000, 400,000, 800,000 and 1,600,000 times plus `b` grew about x2 per doubling, linear, and so did every pattern in `backtracking-red-flags` (about x2 per doubling across the eight, with run-to-run scatter). GNU `grep -E` returned 0 matches for 800,000 `a` plus `b` at once. An automaton engine keeps all live states in step with the input, so there is no tree of alternatives to explore; the diagram shows the two searches side by side.
  • Red flag 1, nested quantifier: a group that contains `+` or `*` and is itself repeated, such as `(a+)+`, `(a*)*`, `(\w+\s?)*` or `([\w.]+)*@`. Red flag 2, overlapping alternation under a repeat: `(a|a)*`, `(a|aa)+`, `(\d|\d\d)+`, branches that can consume the same text. Red flag 3, a group that can match anything or nothing, repeated: `(.*)*`, `(a?)*`. The question that finds all three: is there more than one way to match this substring, and can the overall match still fail afterwards?
  • Not every blow-up is exponential. `\s+$` on n spaces followed by `x` is quadratic (x3.4 to x4.2 per doubling for n = 2,000..16,000 on Python, x3.9 to x4.0 on Node) and `.*.*=.*` on text without `=` is cubic (x7.7 to x7.9 per doubling on Python, x8.3 to x8.4 on Node, n = 2,000..4,000): adjacent quantifiers that can consume the same characters multiply. A quadratic pattern on a large input still costs seconds, and it looks innocent in review.
  • PCRE2 turns a hang into an error. `grep -P` (GNU grep 3.11, PCRE2 10.42) on `^(a+)+$` printed 0 for 22 `a` plus `b` and `grep: (standard input): exceeded PCRE's backtracking limit` with exit status 2 for 23. Treat that error as 'could not decide', never as 'no match'. PCRE2 also skips work when a required literal is missing: `^(.*)*x` on a subject without `x` returned at once, while `^(.*)*x$` on 20 `a` plus `xb` hit the limit, so a test subject must contain the pattern's literals to expose the problem.
  • Fix 1, remove the ambiguity (best): `^(a+)+$` becomes `^a+$`, `^(a|aa)+$` becomes `^a+$`, `^(\w+\s?)*$` becomes `^(?:\w+\s)*\w*$`, `^([\w.]+)*@example\.com$` becomes `^[\w.]*@example\.com$`, `^(.*)*x$` becomes `^.*x$`, and a trailing-whitespace trim `\s+$` becomes `rstrip()`, `strings.TrimRight` or `trimEnd()` in code. Each regex pair was compared on every string up to length 8 over a small alphabet (511 or 9,841 strings per pair): 0 mismatches. The rewrites grew x2 per doubling at n = 100,000..800,000 on Python 3.13.
  • Fix 2, atomic group or possessive quantifier where the engine has one: Python 3.11+ and PCRE2. `^(?>a+)+$` and `^(?:a++)+$` grew x2 per doubling (n = 100,000..800,000 on Python) and `grep -P '^(?>a+)+$'` answered 0 at once on 40 `a` plus `b`. JavaScript and Go have neither; in V8 a lookahead plus backreference does the same, `^(?:(?=(a+))\1)+$`, and was linear on Node. It is a semantic change, not a free speed-up: on Python 3.13 `(?>a*)a` finds nothing in `aaa` while `a*a` matches, so check both a matching and a failing input after the rewrite (see atomic-and-possessive).
  • Anchoring and length caps are mitigations, not fixes. An unanchored `(a+)+$` was only about 2x slower than the anchored form at n = 18..22 on Python and Node (later start positions have shorter tails) and kept growing x4 per two characters. A cap on input length helps only if it sits below the blow-up, and 28 characters already take on the order of ten seconds on Python 3.13, so cap the length and fix the pattern; cap the pattern length too when users supply patterns.
  • Fix 3, a linear engine for untrusted patterns or inputs: Go `regexp` (observed), Rust `regex`, `grep -E`, and RE2 bindings such as the `re2` package for Node and `google-re2` for Python (per their documentation; not run here). It removes the problem without analysing the pattern and costs the backtracking-only syntax (engine-families, re2-unsupported-syntax).
  • Fix 4, a timeout where the platform has one. Python `re` has none built in, but `signal.setitimer` interrupted `^(a+)+$` on 40 `a` plus `b` after 1 s (Linux, main thread, observed; per the docs SIGALRM does not exist on Windows), and terminating a worker process also works (observed with `multiprocessing`). The third-party `regex` package (2026.9.29) accepts `timeout=`: `regex.search(r"^(a|aa)+$", "a" * 60 + "b", timeout=0.5)` raised `TimeoutError: regex timed out`, though its optimizer answered `^(a+)+$` on 40 `a` at once, so a timeout is a backstop. Node: `vm.runInNewContext(code, {}, { timeout: 300 })` gave `ERR_SCRIPT_EXECUTION_TIMEOUT`, and `node --enable-experimental-regexp-engine-on-excessive-backtracks` made `/^(a+)+$/` return `false` at once (experimental flag; observed on Node 22 only). .NET has a per-Regex match timeout (documented; not run here). Go `regexp` has no timeout parameter and does not need one.
  • Detect by timing, not by reading. Grow n, print the ratio against the previous size and look for x2 per doubling (linear), x4 (quadratic), x8 (cubic) or a ratio that stays above x2 per added character (exponential); always include a near-miss subject. The site tool 'Regex ReDoS Detector' (path /tools/regex-redos-detector) does this for a JavaScript pattern in a browser worker, according to its description (not exercised here). Reading is unreliable: `\s+$` and `(\w+\s?)*` look harmless.

Examples

Go
import (
    "errors"
    "regexp"
    "strings"
    "testing"
)

// RE2 bounds the work per input byte, so the classic ReDoS pattern is safe to
// run on hostile input. What is left to guard is size, not exponential time.
const maxInputBytes = 1 << 20

var errInputTooLong = errors.New("input too long")

var nested = regexp.MustCompile(`^(a+)+$`)

func matchNested(s string) (bool, error) {
    if len(s) > maxInputBytes {
        return false, errInputTooLong
    }
    return nested.MatchString(s), nil
}

func TestHostileInputStaysLinear(t *testing.T) {
    hostile := strings.Repeat("a", maxInputBytes-1) + "b"
    ok, err := matchNested(hostile)
    if err != nil || ok {
        t.Fatalf("got (%v, %v), want (false, nil)", ok, err)
    }
    if _, err := matchNested(hostile + "bb"); !errors.Is(err, errInputTooLong) {
        t.Fatalf("got %v, want errInputTooLong", err)
    }
}

Time `^(a+)+$` on a-runs of growing length and print the ratio against the run two characters shorter; about x4 per step means exponential.

Python
import re
import time


def best_time(rx, text, repeat=3):
    best = float("inf")
    for _ in range(repeat):
        start = time.perf_counter()
        rx.search(text)
        best = min(best, time.perf_counter() - start)
    return best


rx = re.compile(r"^(a+)+$")
previous = None
for n in range(16, 29, 2):
    took = best_time(rx, "a" * n + "b")
    print(f"n={n}" + (f"  x{took / previous:.1f} vs n-2" if previous else ""))
    previous = took

# Python 3.13.16 (one run, ratios are the point):
# n=16
# n=18  x3.9 vs n-2
# n=20  x4.1 vs n-2
# n=22  x3.9 vs n-2
# n=24  x4.1 vs n-2
# n=26  x4.2 vs n-2
# n=28  x4.3 vs n-2

The same measurement on V8: the ratio per two characters is also about x4.

javascript
const rx = /^(a+)+$/;
let previous = null;
for (let n = 16; n <= 30; n += 2) {
    const text = "a".repeat(n) + "b";
    let best = Infinity;
    for (let i = 0; i < 3; i++) {
        const start = process.hrtime.bigint();
        rx.test(text);
        best = Math.min(best, Number(process.hrtime.bigint() - start) / 1e9);
    }
    console.log(`n=${n}` + (previous ? `  x${(best / previous).toFixed(1)} vs n-2` : ""));
    previous = best;
}

// Node v22.22.0 (one run): n=16, then x3.8 x4.1 x4.0 x4.3 x4.5 x3.7 x3.9 for n=18..30

Python 3.13 fixes: an unambiguous rewrite, an atomic group (not always equivalent), and a SIGALRM timeout for code that cannot change the pattern.

Python
import re
import signal

# 1. Remove the ambiguity: the same language, linear time.
print(re.search(r"^a+$", "a" * 100_000 + "b"))

# 2. Atomic group or possessive quantifier (Python 3.11+): linear, not always equivalent.
print(re.search(r"^(?>a+)+$", "a" * 100_000 + "b"))
print(re.search(r"(?>a*)a", "aaa"), re.search(r"a*a", "aaa"))


# 3. A timeout when the pattern cannot change (Unix, main thread only).
def on_alarm(signum, frame):
    raise TimeoutError("regex took longer than 1 s")


signal.signal(signal.SIGALRM, on_alarm)
signal.setitimer(signal.ITIMER_REAL, 1.0)
try:
    re.search(r"^(a+)+$", "a" * 40 + "b")
except TimeoutError as err:
    print(err)
finally:
    signal.setitimer(signal.ITIMER_REAL, 0)

# Python 3.13.16 output:
# None
# None
# None <re.Match object; span=(0, 3), match='aaa'>
# regex took longer than 1 s

Node 22: the lookahead-plus-backreference stand-in for an atomic group, and a `vm` timeout around a pattern that must stay.

javascript
const vm = require("node:vm");

// V8 has no (?>...): a lookahead plus a backreference commits to the same text.
const hostile = "a".repeat(100000) + "b";
console.log(/^(?:(?=(a+))\1)+$/.test(hostile));

// A timeout around code that must keep a risky pattern; vm interrupts the regex.
try {
    vm.runInNewContext('/^(a+)+$/.test("a".repeat(40) + "b")', {}, { timeout: 300 });
} catch (err) {
    console.log(err.code, err.message);
}

// Node v22.22.0 output:
// false
// ERR_SCRIPT_EXECUTION_TIMEOUT Script execution timed out after 300ms

The PCRE2 match limit under `grep -P`, and the experimental V8 fallback flag.

bash
# GNU grep 3.11 (PCRE2 10.42): the match limit turns a hang into exit status 2
printf 'aaaaaaaaaaaaaaaaaaaaaab\n' | grep -cP '^(a+)+$'; echo "exit=$?"
# 0
# exit=1
printf 'aaaaaaaaaaaaaaaaaaaaaaab\n' | grep -cP '^(a+)+$'; echo "exit=$?"
# grep: (standard input): exceeded PCRE's backtracking limit
# exit=2

# Node 22: an experimental V8 flag falls back to a linear engine after too many backtracks
node --enable-experimental-regexp-engine-on-excessive-backtracks -p '/^(a+)+$/.test("a".repeat(40) + "b")'
# false

In practice

  • Cloudflare WAF — Its post-incident write-up of the 2 July 2019 outage attributes the CPU exhaustion to a WAF rule regex with heavy backtracking and says the engine would move to RE2 or Rust's `regex`; the rules language is now documented as Rust-regex based, so there is no lookaround or backreference to abuse (per Cloudflare's public documentation; not run here).
  • Stack Overflow — Its public postmortem of the 20 July 2016 outage traced it to a whitespace-trimming regular expression applied to a post with a very long run of whitespace, the same quadratic shape as `\s+$` above (per the postmortem; the incident was not reproduced here).
  • PCRE2 — The library behind `grep -P` has a match limit that turns runaway backtracking into an error: `exceeded PCRE's backtracking limit` at 23 `a` for `^(a+)+$`, exit status 2 (observed on PCRE2 10.42).
  • V8 Irregexp — A matching call runs on the calling thread, so in Node a catastrophic pattern blocks the event loop (exponential trend observed on Node 22.22); `vm` timeouts and the experimental linear fallback flag are the only built-in guards.
  • Go regexp — Matching time is linear in input size, so none of the eight table patterns hung on 1,600,000 characters (observed on Go 1.24.7); the remaining risks are huge patterns and huge inputs, not exponential time.
  • ModSecurity — Exposes directives that limit PCRE match and recursion work per rule, because its rule sets run PCRE-family patterns on attacker-controlled input (per the reference manual; not run here).

Trade-offs

Pros

  • Most red-flag patterns have an equivalent unambiguous form that is shorter, and the rewrite can be checked mechanically against the original on a small alphabet.
  • Linear engines (Go, RE2, `grep -E`) make the question moot for untrusted patterns and inputs.
  • PCRE2's match limit, Python `signal` or `regex` timeouts and Node `vm` timeouts turn a hang into an error the caller can handle.

Cons

  • Reading a pattern is an unreliable detector: `\s+$` is quadratic and `(\w+\s?)*` is exponential, and neither looks dangerous; only a near-miss input at growing size shows it.
  • Limits and timeouts act after the CPU is spent, differ per platform (Python `re` and V8 have no built-in match timeout) and an error is not a negative match.
  • Atomic and possessive fixes change what matches and do not exist in JavaScript or Go; length caps help only below the blow-up; linear engines drop lookaround and backreferences.

Anchoring, literal prefixes, leading `.*`, alternation versus a character class, capture groups and precompiling, each measured as a ratio with `go test -bench` on Go 1.24 and `timeit` on Python 3.13, plus what the numbers do not support.

The problem

A correct regex can still be the hot spot of a service: it runs per line, per request, per log record. Most of its cost comes from a few decisions: where a match may start, whether the engine can jump to a literal, whether a leading `.*` forces a retry from every position, how many groups allocate, and whether the pattern is compiled once. The measurements below are ratios and allocation counts on Go 1.24.7 and Python 3.13.16; absolute times depend on the machine, so none are quoted, and they are not claims about other engines.

How it works

  • Method: benchmark the miss. Most lines in a log filter do not match, and a miss exposes the scanning cost that a hit can hide. The subject below is a 4 KB line of lowercase words with no capital letters, digits or the word `needle`. Go: `go test -bench . -benchmem`, Python: `timeit` minimum of 5 repeats; change one thing per comparison. Ratios were stable across runs, absolute times were not, so only ratios and allocs/op appear here.
  • Anchor when the meaning is 'starts with'. `^[A-Z]+ \d` against the same pattern without `^` took about x800 to x1000 less time in Go (the anchored program fails at the first byte; the other tries every start position) and about x300 less in Python. An anchor changes meaning, so use it for validation and prefix checks, not as a blind speed-up (anchors-and-boundaries). A pattern that already starts with a literal gets most of the benefit from the prefix skip described next.
  • Start with a literal. `needle\d+` ran at the same speed as the bare `needle` in Go and was about x65 to x80 faster than `[nN]eedle\d+` and than `\d+needle`; in Python it was x16 and x27 faster. The engine extracts the literal prefix and finds candidates with a fast substring search: Go reports it with `LiteralPrefix()` (`needle\d+` gives `needle`; `[nN]eedle\d+`, `(?i)needle`, `\d+needle` and `.*needle` give an empty prefix) and Python's `re.DEBUG` prints a `prefix` line only for `needle\d+`. Case-insensitive and class-first patterns lose it, so put a required literal first and keep flags off when you can.
  • Avoid a leading `.*`. `.*needle` was about x90 to x115 slower than `needle` on the 4 KB line in Go and thousands of times slower in Python (x7,000 on 4 KB), where it also scales badly: the time grew x4.0 from 1 KB to 2 KB and x3.5 from 2 KB to the full 3.9 KB. `.*` runs to the end of the line and backs off at every start position. For 'contains', drop it, since search already scans; for the position, capture the part you want.
  • Alternation versus a class is not a speed lever in these engines. `(?:x|y|z|q)\d` against `[xyzq]\d` and `(?:cat|car|cap|cab)\d` against `ca[tprb]\d` ran at the same speed in Go (the parser merges single-character branches and factors the common prefix `ca`) and in Python (ratios 0.95 to 1.05). Reordering six long words changed nothing measurable in either. Order does decide which branch wins in leftmost-first engines (wrong-match-playbook), and ambiguous branches under a repeat are the real hazard (catastrophic-backtracking). Rewrite for clarity and ambiguity, not for speed.
  • Ask for groups only when you use them. `FindStringSubmatch` on `(\w+) (\w+) (\w+)` cost 2 allocs/op in Go; the same pattern without capturing groups through `MatchString` cost 0 allocs/op and ran about x1.6 to x1.7 faster. Use `(?:...)` for grouping, `MatchString` for yes/no, and the `Index` forms to slice the input without copying (go-regexp-api).
  • Compile once. Go: a package-level `regexp.MustCompile` against compiling inside the loop is 0 versus 37 allocs/op and about two orders of magnitude (go-regexp-performance has the benchmark). Python: a module-level `re.compile` call was x1.8 to x2.4 faster than `re.match(pattern, text)`, which hits the module cache (a lookup per call), and compiling on every call after `re.purge()` was x119 to x174 slower. The cache is bounded (512 entries on 3.13.16, a private `re._MAXCACHE`), so patterns built per user can thrash it: hold the compiled objects in your own dict.
  • Shape the input too. Split into lines or records first, so that anchors work, `.` never has to cross a megabyte and a backtracking engine never keeps state for a whole file; prefer `finditer` or the `Index` forms to slicing and copying every match. If the job is a fixed string, `strings.Contains`, `HasPrefix` or `Cut` beat any regex (go-regexp-performance), and a profile (`go test -cpuprofile`, pprof) shows whether the regex is the cost at all before you tune it.

Examples

Go
import (
    "regexp"
    "strings"
    "testing"
)

// A 4 KB line of lowercase words: no "needle", no digits, no capital letters.
var line = strings.Repeat("the quick brown fox jumps over the lazy dog ", 90)

var matched bool

func bench(b *testing.B, pattern, text string) {
    re := regexp.MustCompile(pattern)
    b.ReportAllocs()
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        matched = re.MatchString(text)
    }
}

func BenchmarkUnanchored(b *testing.B)       { bench(b, `[A-Z]+ \d`, line) }
func BenchmarkAnchored(b *testing.B)         { bench(b, `^[A-Z]+ \d`, line) }
func BenchmarkBareLiteral(b *testing.B)      { bench(b, `needle`, line) }
func BenchmarkLiteralPrefix(b *testing.B)    { bench(b, `needle\d+`, line) }
func BenchmarkClassFirst(b *testing.B)       { bench(b, `[nN]eedle\d+`, line) }
func BenchmarkDigitsFirst(b *testing.B)      { bench(b, `\d+needle`, line) }
func BenchmarkLeadingDotStar(b *testing.B)   { bench(b, `.*needle`, line) }
func BenchmarkAlternationWords(b *testing.B) { bench(b, `(?:cat|car|cap|cab)\d`, line) }
func BenchmarkClassWords(b *testing.B)       { bench(b, `ca[tprb]\d`, line) }
func BenchmarkAlternationChars(b *testing.B) { bench(b, `(?:x|y|z|q)\d`, line) }
func BenchmarkClassChars(b *testing.B)       { bench(b, `[xyzq]\d`, line) }

func BenchmarkCaptureGroups(b *testing.B) {
    re := regexp.MustCompile(`(\w+) (\w+) (\w+)`)
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        _ = re.FindStringSubmatch("the quick brown")
    }
}

func BenchmarkNoCaptureGroups(b *testing.B) {
    re := regexp.MustCompile(`\w+ \w+ \w+`)
    b.ReportAllocs()
    for i := 0; i < b.N; i++ {
        matched = re.MatchString("the quick brown")
    }
}

Run the Go benchmarks above; allocation counts and ratios observed on Go 1.24.7 (times intentionally omitted).

bash
go test -bench . -benchmem -count=1
# Go 1.24.7, 4 KB subject. Allocations per operation; times only as ratios (three runs agreed):
# BenchmarkUnanchored          0 allocs/op   about x800 to x1000 slower than BenchmarkAnchored
# BenchmarkAnchored            0 allocs/op
# BenchmarkBareLiteral         0 allocs/op
# BenchmarkLiteralPrefix       0 allocs/op   same as the bare literal; about x65 to x80 faster than BenchmarkClassFirst
# BenchmarkClassFirst          0 allocs/op
# BenchmarkDigitsFirst         0 allocs/op   about x60 to x80 slower than BenchmarkLiteralPrefix
# BenchmarkLeadingDotStar      0 allocs/op   about x90 to x115 slower than the bare literal
# BenchmarkAlternationWords    0 allocs/op   same as BenchmarkClassWords
# BenchmarkAlternationChars    0 allocs/op   same as BenchmarkClassChars
# BenchmarkCaptureGroups       2 allocs/op   about x1.6 to x1.7 slower than BenchmarkNoCaptureGroups
# BenchmarkNoCaptureGroups     0 allocs/op

The same comparisons in Python 3.13 with `timeit`, as ratios against the bare literal.

Python
import re
import timeit

line = "the quick brown fox jumps over the lazy dog " * 90


def per_call(pattern: str, number: int = 1000) -> float:
    rx = re.compile(pattern)
    return min(timeit.repeat(lambda: rx.search(line), number=number, repeat=5)) / number


base = per_call(r"needle")
for pattern in [r"needle\d+", r"[nN]eedle\d+", r"\d+needle", r".*needle", r"^[A-Z]+ \d", r"[A-Z]+ \d", r"ca[tprb]\d", r"(?:cat|car|cap|cab)\d"]:
    print(f"{pattern:<24}{per_call(pattern) / base:9.2f}x")

# Python 3.13.16, ratio against the bare literal `needle` on a 4 KB line (two runs agreed to about 10%):
# needle\d+                    1.0x
# [nN]eedle\d+                16x
# \d+needle                   27x
# .*needle                  7000x
# ^[A-Z]+ \d                   0.1x to 0.2x
# [A-Z]+ \d                   30x
# ca[tprb]\d                   1.0x
# (?:cat|car|cap|cab)\d        1.0x

Precompiling in Python: the module cache costs a lookup per call, and compiling every call is far worse.

Python
import re
import timeit

pattern, text = r"^GET (\S+) HTTP", "GET /api/v1/users HTTP/1.1"
compiled = re.compile(pattern)


def per_call(fn, number):
    return min(timeit.repeat(fn, number=number, repeat=5)) / number


def cold():
    re.purge()
    return re.match(pattern, text)


hot = per_call(lambda: compiled.match(text), 20000)
print(f"module function, cache hit: x{per_call(lambda: re.match(pattern, text), 20000) / hot:.1f}")
print(f"compile on every call:      x{per_call(cold, 2000) / hot:.0f}")

# Python 3.13.16, three runs: x1.8, x2.4 and x2.3 for the cache hit, x119, x171 and x174 for compiling every call

In practice

  • Go regexp — Picks a one-pass, bounded-backtrack or NFA matcher per pattern and uses the literal prefix as a fast skip; `LiteralPrefix()` shows what it found. Benchmarks and allocation counts here come from Go 1.24.7.
  • Python re — Compiles to a bytecode with an INFO header (`re.DEBUG` prints a `prefix` for `needle\d+` only) and caches compiled patterns by string (512 entries on 3.13.16), so the module-level functions cost a cache lookup per call; precompile hot patterns.
  • ripgrep — Extracts literals from the pattern and searches for them before running the regex engine, which is why a required literal first is the cheapest pattern shape (per its documentation; not run here).
  • pprof — `go test -cpuprofile` or a live profile shows `regexp.(*Regexp).doExecute` or `regexp.compile` frames, the usual evidence that a regex is the cost or that it is being compiled in a handler.

Trade-offs

Pros

  • The big wins (an anchor, a literal first, no leading `.*`, compiling once) are one-line changes with ratios of x10 to x1000 on a miss.
  • Ratios and allocs/op transfer between machines far better than nanoseconds, and a benchmark file next to the pattern keeps the claim checkable.
  • Several popular tweaks (alternation to class, branch reordering) measured as no-ops, so they can be dropped from review checklists.

Cons

  • Anchors and literal-first rewrites change what matches or how readable the pattern is, and the gains depend on the subject: a hit, a short line or a different engine can erase them.
  • The numbers cover Go 1.24.7 and Python 3.13.16 on one 4 KB shape of input; other engines (V8, PCRE2 with JIT, Rust) were not measured here and have their own optimizers.
  • Micro-tuning a regex that is not the bottleneck costs readability; profile first and consider `strings` functions or a parser.

Comment mode where the engine has it (Python `re.VERBOSE`, PCRE `x`), composing named parts where it does not (Go, JavaScript), named groups, table-driven tests for each part, and which inline flags `(?i)` and `(?s)` work where.

The problem

A 150-character pattern with six groups reads as noise, and the next person to touch it either rewrites it or leaves it alone forever. Readability comes from three techniques: comment mode where the engine has one, composition from named, individually tested parts where it does not, and named groups everywhere. Each has engine-specific traps: whitespace and `#` are syntax in verbose mode, the string-literal layer in front of the engine eats backslashes, and a flag spelled in one engine is a compile error in another.

How it works

  • Python `re.VERBOSE` (`re.X`) ignores unescaped whitespace and everything from `#` to the end of the line, except inside a character class. Observed on 3.13.16: `re.search(r"a b # c", "ab", re.X)` matched `ab`; `a[ ]b` matched `a b`; `a#b` matched only `a` because `#b` is a comment; `a\#b` matched `a#b`. A literal space is `\ ` or `[ ]`. Use a raw triple-quoted string, put one logical unit per line and write the reason (the policy) in the comment, not a restatement of the token.
  • PCRE2 has the same mode as `(?x)` (and `xx`, which also ignores blanks inside a class); `grep -P '(?x) a b # note'` matched `ab` and `(?x) a [ ]b` matched `a b` (GNU grep 3.11, PCRE2 10.42). The comment group `(?#note)` is accepted by PCRE2 and Python, and rejected by Go (`invalid or unsupported Perl syntax: `(?#``) and by Node 22 (`Invalid group`).
  • Go has no `x` flag: `(?x)` fails with `invalid or unsupported Perl syntax: `(?x``. Build the pattern from named constants and join them (`strings.Join` or `+`, one part per line with a `//` comment). Test every part alone with `^(?:part)$` before it is embedded; the `(?:...)` wrapper stops a part containing `|` from leaking into its neighbours. Extract with named groups and `SubexpIndex` instead of numbers (go-named-captures).
  • JavaScript has no `x` flag and, on Node 22.22.0, no inline flags or comment groups at all: `(?i)abc`, `(?i:a)b` and `(?#note)ab` each throw `Invalid group`. Compose with the `.source` of regex literals, `new RegExp([/^(?<year>\d{4})/.source, /-(?<month>0[1-9]|1[0-2])/.source].join(""))`, so each part is a real literal that the editor highlights and no backslash is doubled, and pass the flags as the second argument.
  • The string layer is the usual breakage in JavaScript: `new RegExp("^\d{4}").source` is `^d{4}` (and `.test("2026")` is false), while `"^\\d{4}"` and a `String.raw` template both give `^\d{4}`. The same holds for a normal Python string (`"\bfoo\b"` contains backspace characters, so use `r"..."`) and a Go interpreted string (`"\d"` does not compile); see no-match-playbook.
  • Inline flags differ by engine (the table `flags-compare` has the full list). Go: `(?i)` `(?s)` `(?m)` `(?U)` anywhere, scoped `(?i:...)`, and `(?-i)`; observed `a(?i)bc` matches `aBC` while `a(?i:b)c` does not. Python 3.13: `(?i)` only at the very start (otherwise `global flags not at the start of the expression at position 1`), scoped `(?i:b)` anywhere. PCRE2: any position (`a(?i)bc` matched `aBC`). JavaScript: none, use the `i`, `s`, `m`, `u` flags on the object. When a pattern is stored in config where flags cannot travel, prefer a form that works in the consuming engine and say which one.
  • Named groups survive refactoring where numbers do not: Python `m.groupdict()` (`(?P<name>...)` only), JavaScript `m.groups` (`(?<name>...)` only), Go `SubexpIndex` (both spellings). Keep the names stable, use them in replacements, and prefer them over comments that describe group 3.
  • Test the parts, then the whole. A table of accept and reject inputs per part (the Go sketch) catches the typo in one component without staring at the joined pattern, and a failing test message names the part. Keep a few near-miss rejects (`10.0.0`, status `604`) beside the accepts; they are the cases that go wrong in production (validate-vs-extract).

Examples

Go
import (
    "regexp"
    "strings"
    "testing"
)

// Go has no x flag, so a long pattern is joined from named parts. Each part is
// a constant that can be tested alone before it is embedded.
const (
    ipPart     = `\d{1,3}(?:\.\d{1,3}){3}`
    tsPart     = `[^\]]+`
    methodPart = `[A-Z]+`
    pathPart   = `\S+`
    statusPart = `[1-5]\d\d`
)

var logLine = regexp.MustCompile(strings.Join([]string{
    `^(?P<ip>` + ipPart + `)`,
    ` - `,
    `\[(?P<ts>` + tsPart + `)\]`,
    ` "(?P<method>` + methodPart + `) (?P<path>` + pathPart + `)"`,
    ` (?P<status>` + statusPart + `)$`,
}, ""))

func TestParts(t *testing.T) {
    tests := []struct {
        name string
        part string
        in   string
        want bool
    }{
        {"ip ok", ipPart, "10.0.0.7", true},
        {"ip short", ipPart, "10.0.0", false},
        {"status ok", statusPart, "204", true},
        {"status 6xx", statusPart, "604", false},
        {"method lower", methodPart, "get", false},
    }
    for _, tc := range tests {
        re := regexp.MustCompile(`^(?:` + tc.part + `)$`)
        if got := re.MatchString(tc.in); got != tc.want {
            t.Errorf("%s: %q matched=%v, want %v", tc.name, tc.in, got, tc.want)
        }
    }
}

func TestLogLine(t *testing.T) {
    line := `10.0.0.7 - [11/Oct/2026:10:00:00 +0000] "GET /a?x=1#top" 200`
    m := logLine.FindStringSubmatch(line)
    if m == nil {
        t.Fatal("no match")
    }
    if got := m[logLine.SubexpIndex("path")]; got != "/a?x=1#top" {
        t.Errorf("path = %q", got)
    }
    if got := m[logLine.SubexpIndex("status")]; got != "200" {
        t.Errorf("status = %q", got)
    }
}

Python 3.13: `re.VERBOSE` with comments and named groups, the whitespace and `#` rules, and where inline flags may go.

Python
import re

LOG = re.compile(
    r"""
    ^(?P<ip>\d{1,3}(?:\.\d{1,3}){3})         # client address
    \s+-\s+
    \[(?P<ts>[^\]]+)\]                        # timestamp; the ] needs an escape inside a class
    \s+"(?P<method>[A-Z]+)\ (?P<path>\S+)"    # a literal space is "\ " (or "[ ]")
    \s+(?P<status>[1-5]\d\d)                  # status code
    \s*$
    """,
    re.VERBOSE,
)
line = '10.0.0.7 - [11/Oct/2026:10:00:00 +0000] "GET /a?x=1#top" 200'
print(LOG.match(line).groupdict())

# In verbose mode whitespace and # are syntax, except inside a character class.
print(re.search(r"a b # c", "ab", re.X).group())
print(re.search(r"a[ ]b", "a b", re.X).group())
print(re.search(r"a#b", "a#b", re.X).group())
print(re.search(r"a\#b", "a#b", re.X).group())

# Inline flags: global ones must come first, scoped ones can go anywhere.
print(re.search(r"(?i)abc", "xABC").group(), re.search(r"a(?i:b)c", "aBc").group())
try:
    re.compile(r"a(?i)bc")
except re.error as err:
    print(err)

# Python 3.13.16 output:
# {'ip': '10.0.0.7', 'ts': '11/Oct/2026:10:00:00 +0000', 'method': 'GET', 'path': '/a?x=1#top', 'status': '200'}
# ab
# a b
# a
# a#b
# ABC aBc
# global flags not at the start of the expression at position 1

Node 22: compose from regex literals with `.source`, the string-literal escape trap, and the absence of inline flags.

javascript
// No x flag and no inline flags in V8: join regex literals through .source, flags go last.
const parts = [
    /^(?<year>\d{4})/.source, // year
    /-(?<month>0[1-9]|1[0-2])/.source, // month
    /-(?<day>0[1-9]|[12]\d|3[01])$/.source, // day
];
const date = new RegExp(parts.join(""));
console.log(date.source);
console.log(date.test("2026-10-11"), date.test("2026-13-01"), date.exec("2026-10-11").groups.month);

// The string-literal layer eats the backslash.
console.log(new RegExp("^\d{4}").source, new RegExp("^\\d{4}").source, new RegExp(String.raw`^\d{4}`).source);

// Node 22.22.0 has no inline flags or comment groups: the flag is a constructor argument.
for (const source of ["(?i)abc", "(?i:a)b", "(?#note)ab"]) {
    try {
        new RegExp(source);
    } catch (err) {
        console.log(err.message);
    }
}
console.log(new RegExp("abc", "i").test("ABC"), /a.b/s.test("a\nb"));

// Node v22.22.0 output:
// ^(?<year>\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[12]\d|3[01])$
// true false 10
// ^d{4} ^\d{4} ^\d{4}
// Invalid regular expression: /(?i)abc/: Invalid group
// Invalid regular expression: /(?i:a)b/: Invalid group
// Invalid regular expression: /(?#note)ab/: Invalid group
// true true

In practice

  • Python re — `re.VERBOSE` is the documented way to comment a long pattern; scoped `(?i:...)` and a start-of-pattern `(?i)` are the only inline flag forms on 3.13.16 (observed).
  • PCRE2 — `(?x)`, `xx` and `(?#...)` comments plus inline flags at any position, observed through `grep -P` (GNU grep 3.11, PCRE2 10.42).
  • Go regexp — No `x` mode, no comment group; composition from constants plus table-driven tests is the idiom, and `SubexpIndex` (Go 1.15) replaces magic group numbers. Observed on Go 1.24.7.
  • V8 Irregexp — Flags only on the object (`d g i m s u v y`), no inline modifiers on Node 22.22.0; `RegExp.prototype.source` is what makes composing from literals safe.
  • ESLint — Ships rules such as `prefer-named-capture-group` and `require-unicode-regexp` that push regex literals toward named groups and explicit flags (per its rule documentation; not run here).

Trade-offs

Pros

  • Verbose mode and composed parts turn one opaque line into reviewable pieces with comments that explain the policy.
  • Per-part tests localise a bug to one constant and keep accept and reject cases next to the code.
  • Named groups remove positional coupling between the pattern and the code that reads it.

Cons

  • Verbose mode changes the meaning of space and `#`, so a pattern pasted between verbose and normal contexts silently changes.
  • Composition is a build step done by hand: precedence leaks between parts unless each is wrapped in `(?:...)`, and the joined text is still what the engine reads.
  • There is no common spelling: Go has no `x`, JavaScript has no inline flags, Python wants global flags first, so a shared pattern needs a per-engine form.

A pattern that should match returns `None`, `null`, `false` or grep exit status 1: check, in order, the escape layers (Go raw strings, `"\d"` in Python and JavaScript, JSON and YAML), the call and anchors, multiline and dot-all, Unicode and hidden characters, and syntax the engine reads differently.

The problem

A pattern that looks right returns nothing: `None`, `null`, `false`, an empty list, or `grep` exiting with status 1. The engine is almost never at fault. Either the pattern text it received differs from the one you typed, or the text it searched differs from the one you see. The checks below run from the cheapest to the most specific, and each step has an input that reproduces it with the output observed on Go 1.24.7, Python 3.13.16, Node v22.22.0 or GNU grep 3.11. A pattern that fails to compile is a different problem (re2-unsupported-syntax); this playbook is for the silent ones.

How it works

  • Symptom: the match call returns its empty value although you can see the text in the input. First decide which side is wrong. Print the pattern as the engine holds it (`re.String()` in Go, `pattern.pattern` in Python, `re.source` in JavaScript) and print the subject with its escapes visible (`%q`, `repr`, `JSON.stringify`, `od -c`). The Go sketch's `explain` prints the compiled pattern, all matches and the group offsets in one call. Python also has `re.compile(p, re.DEBUG)`, which prints the parse tree: for the non-raw `"\bfoo"` it starts with `LITERAL 8`, for `r"\bfoo"` with `AT AT_BOUNDARY`.
  • Step 1, escape layers, Go: `regexp.MustCompile("\d+")` does not build: the compiler says `unknown escape` (`go vet`: `unknown escape sequence`). That is the lucky case. `"\b"`, `"\t"`, `"\n"`, `"\a"` are valid Go escapes and silently become control characters: `regexp.MustCompile("\bfoo\b").MatchString("a foo b")` is false, its `String()` is `"\bfoo\b"` as backspaces, while `` `\bfoo\b` `` matches `foo` at offsets 2 to 5. Use a raw string, or `"\\d"`, and print `%q` of the pattern.
  • Step 1, escape layers, Python and JavaScript: `re.search("\bfoo\b", "a foo b")` is `None` because `"\b"` is a backspace character; `"\\bfoo\\b"` finds `foo`. `"\d"` gives `SyntaxWarning: invalid escape sequence '\d'` on 3.13 (it still works today; with `-W error` it is a `SyntaxError`), so use `r"..."`. In JavaScript `new RegExp("\d+").source` is `d+` and `.test("42")` is false while `"\\d+"` works; and `/\p{L}/` without the `u` flag does not error: it matches the text `p{L}` (`/\p{L}/.test("é")` is false, with `u` it is true).
  • Step 1, escape layers, config and shell: JSON needs `"\\d+"`; `"\d+"` fails (for the document `{"p":"\d+"}`, Python `json`: `Invalid \escape: line 1 column 7 (char 6)`; Node 22: `Bad escaped character in JSON at position 7 (line 1 column 8)`). YAML (PyYAML 6.0.1) double-quoted `"\d+"` fails with `found unknown escape character 'd'`, while plain `\d+` and single-quoted `'\d+'` both load as `\d+`. In the shell, quote the pattern with single quotes, and remember `grep -E` has no `\d`: `printf 'foo 42\n' | grep -oE '\d+'` printed nothing with exit status 1 (it read `d`), `grep -oP '\d+'` printed `42`, `grep -oE '[0-9]+'` printed `42`.
  • Step 2, the call and the anchors. Python `re.match(r"\d+", "id 42")` is `None` because `match` only tries position 0 (`re.search` finds `42`). An anchored pattern must be able to see the whole subject: Go `^\d+$` fails on `" 12"` and on `"12\n"`. Text with CRLF line endings breaks `$` under multiline: Go `(?m)^\d+$` on `12\r\n34` found only `34`, because `$` sits before `\n` and the `\r` is in the way; `(?m)^\d+\r?$` found `12\r` and `34` (the `\r` is now part of the match). `grep -P '^\d+$'` on `12\r\n` printed 0, `'^\d+\r$'` printed 1. Normalize line endings first.
  • Step 3, multiline and dot-all. Without the multiline flag `^` is the start of the input: `^b` on `a\nb` is false in Go, `None` in Python, false in JavaScript, and true with `(?m)`, `re.M` or the `m` flag. `.` does not cross a newline: `a.b` on `a\nb` fails everywhere, and succeeds with `(?s)`, `re.S` or the `s` flag; `[\s\S]` works without any flag. Remember that the flag spelling differs per engine (flags-and-modes).
  • Step 4, Unicode. Go and JavaScript `\w` and `\b` are ASCII-only: Go `\w+` on `café` finds `caf`, and `\bcafé\b` does not match `café au lait` because `é` is not a word character (JavaScript `/\bcafé\b/` is false; Python is true). Use `[\p{L}\p{N}_]+` in Go. `\s` does not match the no-break space U+00A0 in Go or PCRE2 (`printf 'x\xc2\xa0y\n' | grep -cP '\s'` printed 0) but does in Python and JavaScript; add `\x{00a0}` or normalize. Composed and decomposed accents differ: `é` (U+00E9) does not match `e` plus U+0301 in Go, Python or JavaScript; normalize with `unicodedata.normalize("NFC", s)` or `s.normalize("NFC")` (Go: the `golang.org/x/text/unicode/norm` package, not run here). `(?i)é` matches `É` in Go and `/é/i` in JavaScript.
  • Step 5, flags and syntax that is read differently. Case: `foo` does not match `FOO` in Go, while `(?i)foo` does. Syntax that is not an error but not what you meant: Go `a{,2}` is the literal text `a{,2}` (false on `aa`, true on `a{,2}`); Python `[[:digit:]]+` on `a5b` is `None` with `FutureWarning: Possible nested set at position 1`, while `[0-9]+` finds `5`; ERE reads `\d` as `d`. Look the construct up in the table `engine-feature-matrix` before suspecting the text.
  • Step 6, hidden characters in the subject. `printf 'x\xc2\xa0y\n' | od -An -c` prints `x 302 240 y \n`: a no-break space that looks like a space, which `x y` in a pattern will not match. Zero-width spaces, smart quotes, a BOM and `\r` behave the same. Compare bytes, not glyphs, and copy the failing subject into the test as an escaped literal.
  • Fix: shrink to the smallest failing pattern and subject, then change one layer at a time. Verify: the same input now matches, and a near-miss still does not. Prevent: raw strings or `r"..."` for every pattern, `go vet` and `python -W error` in CI, a table-driven accept and reject test beside each pattern (readable-regexes), and anchors written with the call (`fullmatch`) rather than by hand.

Examples

Go
import (
    "fmt"
    "regexp"
)

// explain prints what the engine received and what it found: the compiled
// pattern text, every match, and the byte offsets of the groups.
func explain(pattern, text string) {
    re, err := regexp.Compile(pattern)
    if err != nil {
        fmt.Println("compile:", err)
        return
    }
    fmt.Printf("pattern %q\n", re.String())
    fmt.Printf("matches %q\n", re.FindAllString(text, -1))
    fmt.Println("offsets", re.FindAllStringSubmatchIndex(text, -1))
}

func demo() {
    // "\\d" in an interpreted string and `\d` in a raw string are the same pattern.
    explain("\\d+", "id 42")
    explain(`\d+`, "id 42")
    // "\b" in an interpreted string is a backspace character, not a word boundary.
    explain("\bfoo\b", "a foo b")
    explain(`\bfoo\b`, "a foo b")
    // \r before \n keeps $ from matching under (?m).
    explain(`(?m)^\d+$`, "12\r\n34")
}

// Go 1.24.7 output, in order:
// pattern "\\d+"
// matches ["42"]
// offsets [[3 5]]
// pattern "\\d+"
// matches ["42"]
// offsets [[3 5]]
// pattern "\bfoo\b"
// matches []
// offsets []
// pattern "\\bfoo\\b"
// matches ["foo"]
// offsets [[2 5]]
// pattern "(?m)^\\d+$"
// matches ["34"]
// offsets [[4 6]]

GNU grep 3.11: ERE has no `\d`, and od -c shows a no-break space and a CR that the pattern did not expect.

bash
printf 'foo 42\n' | grep -oE '\d+'; echo "exit=$?"
# exit=1       ERE has no \d: GNU grep read it as the letter d, and found none in "foo 42"
printf 'foo 42\n' | grep -oP '\d+'; echo "exit=$?"
# 42
# exit=0
printf 'foo 42\n' | grep -oE '[0-9]+'
# 42

# Hidden characters: show the bytes, not the glyphs.
printf 'x\xc2\xa0y\n' | od -An -c
#    x 302 240   y  \n        a no-break space (U+00A0) looks like a space
printf 'x\xc2\xa0y\n' | grep -cP '\s'
# 0                           PCRE2 \s does not match it either
printf '12\r\n' | od -An -c
#    1   2  \r  \n
printf '12\r\n' | grep -cP '^\d+$'
# 0                           the \r sits between the digits and the end
printf '12\r\n' | grep -cP '^\d+\r$'
# 1

Python 3.13: the string escape layer, match versus search, anchors, dot-all, composed versus decomposed accents, and a POSIX class that is not an error.

Python
import re
import unicodedata

# 1. The escape layer: "\b" in a normal Python string is a backspace character.
print(re.search("\bfoo\b", "a foo b"))
print(re.search("\\bfoo\\b", "a foo b") is not None)

# 2. Which call? match() only tries position 0.
print(re.match(r"\d+", "id 42"))
print(re.search(r"\d+", "id 42").group())

# 3. Anchors, multiline and dot-all.
print(re.search(r"^b", "a\nb"))
print(re.search(r"^b", "a\nb", re.M).group())
print(re.search(r"a.b", "a\nb"))
print(re.search(r"a.b", "a\nb", re.S) is not None)

# 4. Unicode: composed vs decomposed e-acute.
decomposed = "é"
print(re.search("é", decomposed))
print(re.search("é", unicodedata.normalize("NFC", decomposed)) is not None)

# 5. Syntax that does not exist is not always an error.
print(re.search(r"[[:digit:]]+", "a5b"))
print(re.search(r"[0-9]+", "a5b").group())

# Python 3.13.16 output, in order (step 5 also warns on stderr:
# FutureWarning: Possible nested set at position 1):
# None
# True
# None
# 42
# None
# b
# None
# True
# None
# True
# None
# 5

Node 22: `"\d"` in a string literal, `\p{L}` without `u`, multiline, dot-all and the ASCII-only `\b`.

javascript
// 1. The escape layer: "\d" in a string literal is just "d".
console.log(new RegExp("\d+").source, new RegExp("\\d+").source);
console.log(new RegExp("\d+").test("42"), new RegExp("\\d+").test("42"));

// 2. \p{...} needs the u flag; without it the escape is the letter p.
console.log(/\p{L}/.test("é"), /\p{L}/u.test("é"));

// 3. Anchors, dot-all, and what \b means for non-ASCII letters.
console.log(/^b/.test("a\nb"), /^b/m.test("a\nb"));
console.log(/a.b/.test("a\nb"), /a.b/s.test("a\nb"));
console.log(/\bcafé\b/.test("café au lait"), /é/.test("é"), /é/.test("é".normalize("NFC")));

// Node v22.22.0 output, in order:
// d+ \d+
// false true
// false true
// false true
// false true
// false false true

In practice

  • Go regexp — Raw strings are the idiom; an unknown escape in an interpreted string is rejected at build time, but valid ones such as `\b` and `\t` silently change the pattern. `go vet` reported `unknown escape sequence` on Go 1.24.7.
  • Python re — `re.DEBUG` prints the parsed pattern, and 3.13 warns `SyntaxWarning: invalid escape sequence '\d'` for non-raw strings; `[[:digit:]]` gives `FutureWarning: Possible nested set` (all observed on 3.13.16).
  • V8 Irregexp — Without `u`, unknown escapes are identity escapes and `\p{L}` matches the text `p{L}`; `\b` and `\w` are ASCII-only (observed on Node 22.22.0).
  • GNU grep — Exit status 1 means no match and 2 means an error; `-o` shows the exact span; `-E` has no `\d` while `-P` does (GNU grep 3.11, PCRE2 10.42).
  • PyYAML — Double-quoted YAML strings process backslash escapes, so a regex stored as `"\d+"` fails to load (`found unknown escape character 'd'`, PyYAML 6.0.1); single quotes keep it intact.

Trade-offs

Pros

  • The checks are ordered by cost, so most failures end at step 1 or 2 with a one-line change.
  • Every step has a reproducible input; the same inputs make good regression cases.
  • Printing the held pattern and the escaped subject is engine-independent and needs no tooling.

Cons

  • Several of these failures are silent (`\b` as backspace, `\p{L}` as text, ERE `\d`), so nothing points at the cause until you look at the bytes.
  • Fixes differ per engine (flag spelling, Unicode classes, normalization), so a pattern shared across languages needs a check on each one.
  • Hidden characters in real data (no-break spaces, CR, BOM) cannot be found from the pattern alone and need the failing sample.

A pattern matches too much, the wrong branch, an input it should reject, an extra empty match, or alternates between true and false: look at the spans first, then check unescaped dots, anchors and boundaries, greedy quantifiers, alternation order, empty matches and the JavaScript `g` flag, in that order.

The problem

The pattern matches, but the wrong thing: too much text, the first branch instead of the best one, an input that should have been rejected, an extra empty match in a replacement, or a `test()` that alternates between true and false. These bugs are the engine doing exactly what the pattern says, so the first step is to read the spans, not the boolean. Every step below has an input and the output observed on Go 1.24.7, Python 3.13.16, Node v22.22.0 or GNU grep 3.11 and sed 4.9.

How it works

  • Symptom and first look: print every match with its offsets and groups on a handful of near-miss inputs (Go `FindAllStringSubmatchIndex`, Python `m.span()` or `finditer`, JavaScript `matchAll`, shell `grep -o`). The matched text shows which of the causes below applies: too long (greedy), too early (a shorter branch), too many (unescaped dot, missing boundary), or empty.
  • Step 1, an unescaped metacharacter: `example.com` matched `exampleXcom` in Go and Python, `example\.com` did not. The same goes for `.` in IPs, versions and file names, and for `-` or `]` in classes. Escape with `regexp.QuoteMeta`, `re.escape` or by hand (escaping-rules).
  • Step 2, anchors, boundaries and alternation precedence: `cat` matched twice in `concatenate cat` (Go, `grep -o`), `\bcat\b` and `grep -w` once. `^foo|bar$` is `(^foo)|(bar$)`: on `foox xbar` it found `foo` and `bar` in Go, Python and ERE, and `^(?:foo|bar)$` found nothing. Python `$` accepts a trailing newline (`re.search(r"^\d+$", "12\n")` matched, `re.fullmatch(r"\d+", "12\n")` returned `None`) and `\d` matches Arabic-Indic digits (`^\d+$` on `٣٤` matched, `^[0-9]+$` did not); see anchors-and-boundaries and char-classes-and-escapes.
  • Step 3, greedy quantifiers: `".*"` on `say "hi" and "bye"` matched one string, `"hi" and "bye"`, in Go, Python, JavaScript and ERE; `".*?"` and `"[^"]*"` matched `"hi"` and `"bye"`. The same holds across lines under `(?s)`: Go `(?s)START(.*)END` on two records matched both as one, `(?s)START(.*?)END` matched each. Prefer the negated class when the stop character is known (quantifiers-greedy-lazy).
  • Step 4, alternation order: Perl-family engines take the first branch that lets the whole pattern succeed, not the longest. `in|int|integer` on `integer` matched `in` in Go, Python and `grep -P`; `integer|int|in` and `\b(?:in|int|integer)\b` matched `integer`. POSIX ERE takes the longest: `grep -oE 'in|int|integer'` printed `integer`; Go gets that with `Longest()`. Order branches longest first, or anchor them with a boundary or the end of the pattern (groups-and-captures).
  • Step 5, empty matches: a pattern that can match nothing matches at positions you did not expect. Replacing `a*` with `-` in `baac` gave `-b-c-` in Go and `sed -E`, and `-b--c-` in Python 3.13 and Node 22. `FindAll` for `a*` on `baac` gave `["" "aa" ""]` in Go and `['', 'aa', '', '']` in Python. Splitting `a b` on `\s*` gave `["a" "b"]` in Go, `['a', 'b']` in JavaScript and `['', 'a', '', 'b', '']` in Python. Use `+` unless an empty match is what you want, and test the empty and the adjacent case.
  • Step 6, JavaScript `g` and `y` state: a regex with `g` remembers `lastIndex`, so the same call changes answer. `const isAdmin = /^id-a/g` over four ids that all start with `id-a` returned `true, false, true, false` and left `lastIndex` at 0; the same regex without `g` returned four `true`. Fix by dropping `g` for boolean tests, creating the regex per call, or resetting `lastIndex = 0` (flags-and-modes, python-javascript-gotchas).
  • Step 7, a pattern from another engine: `a+?` is lazy everywhere except ERE, `[]x]` differs in JavaScript, Python `\d` and `$` differ from Go. If the pattern was copied between languages, run the near-miss corpus on the engine you actually ship (portable-subset).
  • Fix: change the pattern, add the failing input to a table-driven test with the exact expected spans (the Go sketch), and keep a few near misses that must not match. Verify the corpus on every engine the pattern runs on. Prevent: anchor validators with `fullmatch` or `^...$`, prefer negated classes to `.*`, escape dots, and review empty-capable patterns used for `replace` or `split`.

Examples

Go
import (
    "reflect"
    "regexp"
    "testing"
)

// Wrong matches are cheapest to catch with the exact spans a pattern returns on
// a few near-miss inputs, kept next to the pattern as a table-driven test.
func TestFindAllCorpus(t *testing.T) {
    tests := []struct {
        name    string
        pattern string
        in      string
        want    []string
    }{
        {"greedy spans both quotes", `".*"`, `say "hi" and "bye"`, []string{`"hi" and "bye"`}},
        {"negated class stops at the quote", `"[^"]*"`, `say "hi" and "bye"`, []string{`"hi"`, `"bye"`}},
        {"first alternative wins", `in|int|integer`, "integer", []string{"in"}},
        {"boundary and longest first", `\b(?:integer|int|in)\b`, "integer", []string{"integer"}},
        {"unescaped dot", `example.com`, "exampleXcom", []string{"exampleXcom"}},
        {"escaped dot", `example\.com`, "exampleXcom", nil},
        {"no boundary", `cat`, "concatenate cat", []string{"cat", "cat"}},
        {"boundary", `\bcat\b`, "concatenate cat", []string{"cat"}},
        {"alternation splits at the anchor", `^foo|bar$`, "foox xbar", []string{"foo", "bar"}},
        {"grouped alternation", `^(?:foo|bar)$`, "foox", nil},
    }
    for _, tc := range tests {
        got := regexp.MustCompile(tc.pattern).FindAllString(tc.in, -1)
        if !reflect.DeepEqual(got, tc.want) {
            t.Errorf("%s: %q on %q = %q, want %q", tc.name, tc.pattern, tc.in, got, tc.want)
        }
    }
}

GNU grep 3.11 and sed 4.9: greedy span, longest versus first alternative, an empty-match replace, anchor precedence and `-w`.

bash
printf 'say "hi" and "bye"\n' | grep -oE '".*"'
# "hi" and "bye"            one greedy match
printf 'say "hi" and "bye"\n' | grep -oE '"[^"]*"'
# "hi"
# "bye"
printf 'integer\n' | grep -oE 'in|int|integer'
# integer                   POSIX ERE takes the longest alternative
printf 'integer\n' | grep -oP 'in|int|integer'
# in                        PCRE2 takes the first one that works
printf 'baac\n' | sed -E 's/a*/-/g'
# -b-c-                     Python 3.13 and Node 22 give -b--c-
printf 'foox xbar\n' | grep -oE '^foo|bar$'
# foo
# bar                       the anchors belong to different branches
printf 'concatenate cat\n' | grep -o 'cat' | wc -l
# 2
printf 'concatenate cat\n' | grep -ow 'cat' | wc -l
# 1

Python 3.13: greedy and lazy spans, alternation order, anchor precedence, an unescaped dot, empty matches, and Unicode digits with a trailing newline.

Python
import re

text = 'say "hi" and "bye"'
print(re.findall(r'".*"', text))
print(re.findall(r'".*?"', text))
print(re.findall(r'"[^"]*"', text))

print(re.findall(r"in|int|integer", "integer"))
print(re.findall(r"\b(?:in|int|integer)\b", "integer"))

print(re.findall(r"^foo|bar$", "foox xbar"))
print(re.findall(r"^(?:foo|bar)$", "foox"))

print(re.search(r"example.com", "exampleXcom") is not None)
print(re.search(r"example\.com", "exampleXcom") is not None)

print(re.sub("a*", "-", "baac"))
print(re.sub("a+", "-", "baac"))
print(re.split(r"\s*", "a b"))
print(re.split(r"\s+", "a b"))

print(re.search(r"^\d+$", "٣٤") is not None)
print(re.search(r"^[0-9]+$", "٣٤") is not None)
print(re.search(r"^\d+$", "12\n") is not None)
print(re.fullmatch(r"\d+", "12\n"))

# Python 3.13.16 output, in order:
# ['"hi" and "bye"']
# ['"hi"', '"bye"']
# ['"hi"', '"bye"']
# ['in']
# ['integer']
# ['foo', 'bar']
# []
# True
# False
# -b--c-
# b-c
# ['', 'a', '', 'b', '']
# ['a', 'b']
# True
# False
# True
# None

Node 22: a `g` regex alternating true and false through `lastIndex`, the empty-match replace and split, and the greedy span.

javascript
// A /g regex keeps lastIndex between calls, so the same input answers differently.
const isAdmin = /^id-a/g;
const ids = ["id-a1", "id-a2", "id-a3", "id-a4"];
console.log(ids.map(id => isAdmin.test(id)));
console.log(isAdmin.lastIndex);

const fixed = /^id-a/;
console.log(ids.map(id => fixed.test(id)));

const reused = /a/g;
console.log(reused.test("a"), reused.lastIndex);
reused.lastIndex = 0;
console.log(reused.test("a"), reused.lastIndex);

console.log("baac".replace(/a*/g, "-"));
console.log("a b".split(/\s*/), "a b".split(/\s+/));
console.log('say "hi" and "bye"'.match(/".*"/g));
console.log('say "hi" and "bye"'.match(/".*?"/g));

// Node v22.22.0 output, in order:
// [ true, false, true, false ]
// 0
// [ true, true, true, true ]
// true 1
// true 1
// -b--c-
// [ 'a', 'b' ] [ 'a', 'b' ]
// [ '"hi" and "bye"' ]
// [ '"hi"', '"bye"' ]

In practice

  • Go regexp — Leftmost-first by default, with `Longest()` for POSIX semantics; skips an empty match adjacent to the previous match, so `a*` on `baac` gives `["" "aa" ""]` (observed on Go 1.24.7).
  • Python re — Since 3.7 (per the changelog) empty matches next to a previous match are allowed (`re.sub("a*", "-", "baac")` is `-b--c-`), `$` tolerates a final newline and `\d` is Unicode-aware (observed on 3.13.16).
  • V8 Irregexp — Same `-b--c-` result as Python; a `g` or `y` regex stores `lastIndex` on the object, so shared module-level regexes make `test()` stateful (observed on Node 22.22.0).
  • GNU grep — `-E` is leftmost-longest (`integer`), `-P` is leftmost-first (`in`); `-o` prints each span and `-w` adds word boundaries (GNU grep 3.11).
  • GNU sed — `sed -E 's/a*/-/g'` on `baac` printed `-b-c-`, the same as Go and different from Python and Node (sed 4.9).

Trade-offs

Pros

  • Reading spans instead of booleans finds the cause quickly: the matched text itself tells whether it is greedy, early, unescaped or empty.
  • Each cause has a one-line fix (escape, anchor, negated class, branch order, `+`, drop `g`) that does not change the rest of the pattern.
  • A table-driven corpus with exact expected spans turns each bug into a permanent regression test on every engine.

Cons

  • Wrong matches pass casual testing, because the happy-path input still works; only near-miss inputs expose them.
  • The same pattern text behaves differently across engines (empty matches, `$`, `\d`, alternation winner), so one engine's fix may not carry over.
  • Fixes such as `Longest()` or reordering branches change results for other inputs and need the whole corpus re-run.