Toolbox Hub
Developer Tools12 min read

Why Your Regex Works in Python and Fails in JavaScript

The same pattern can throw, match nothing, or hang a browser tab depending on the engine. A concrete tour of JavaScript RegExp's flag rules, missing PCRE features, Unicode behaviour and backtracking risk, checked against a working browser regex tester.

What this guide covers

  • 1. The global flag is not optional here
  • 2. Syntax that simply does not exist in JavaScript
  • 3. Unicode needs an explicit flag
  • 4. Anchors and dotall are the quiet portability bugs
  • 5. Backtracking can freeze the whole tab
  • 6. A porting checklist
  • 7. Frequently asked questions
  • 8. The one-line version

A pattern copied from a working Python script is pasted into a browser tool and immediately produces `TypeError: String.prototype.matchAll called with a non-global RegExp argument`. Nothing is wrong with the pattern. The failure is an API contract that only exists in JavaScript, and it is the first of several differences that make regexes one of the least portable things developers move between languages.

The Regex Tester on this site is small enough to make a good case study. It constructs a regex with `new RegExp(pattern, flags)`, then collects results with `[...text.matchAll(re)]`. Both of those lines carry assumptions worth unpacking.

The global flag is not optional here

`String.prototype.matchAll` requires a global regex. Pass it `''`, `'i'` or `'m'` and it throws immediately; `'g'`, `'gi'` and `'gu'` work. That is by design: `matchAll` returns an iterator over *all* matches, and the engine needs `lastIndex` to advance, which only happens for global regexes. The tool defaults the flag field to `g` for exactly this reason, and surfaces the engine's error message rather than swallowing it.

  • Want case-insensitive matching? Type `gi`, not `i`. The tool does not add `g` for you, because silently rewriting flags would hide what the engine is doing.
  • Want multiline anchors? `gm`, not `m`.
  • Want Unicode property escapes? `gu`, not `u`.

Related but separate is the statefulness that `g` introduces elsewhere. A global regex has a mutable `lastIndex`: calling `test()` three times on `/a/g` against `'aa'` gives `true, true, false` because the cursor advanced between calls. Reusing a global regex across functions is a classic source of intermittent bugs. `matchAll` clones the regex internally, so it does not mutate the object you passed in — checking `re.lastIndex` afterwards returns 0 — but `test()` and `exec()` absolutely do.

Syntax that simply does not exist in JavaScript

JavaScript's RegExp is specified by ECMAScript, not by PCRE, and it deliberately omits several constructs that Perl, PHP, Ruby, Java and .NET users reach for. Writing them into a JS pattern produces a `SyntaxError` at construction time, not a failed match:

  • Possessive quantifiers such as `a++` — SyntaxError. There is no way to tell the engine 'never give this back'.
  • Atomic groups such as `(?>...)` — SyntaxError. Same missing capability.
  • `\K` (reset match start) and `\A` / `\z` (absolute anchors) — not part of the language. Use `^` and `$`, with `m` where needed.
  • Named groups use `(?<name>...)` and `groups.name`. Python spells it `(?P<name>...)`; .NET accepts `(?<name>...)`. Copying the Python form into JS gives a syntax error.
  • Lookbehind exists, but only since ES2018. Variable-length lookbehind is allowed in JavaScript (unlike Python, which requires fixed width), while older Safari versions before 16.4 do not support lookbehind at all. A pattern that works in Node can still break in an older browser.

Unicode needs an explicit flag

`\p{L}` is a Unicode property escape, and in JavaScript it is inert without the `u` flag. Test `\p{L}` against `é` with no flag and it returns false — the engine reads it as a literal `p` followed by a quantifier on `{L}` in some positions, or as an identity escape depending on the pattern. Add `u` and it correctly matches the letter. Python's standard `re` module does not support `\p{...}` at all (the third-party `regex` module does), while .NET and Java accept it natively.

The same trap applies to `\d`. In JavaScript it means `[0-9]` only — testing it against the Arabic-Indic digit `٣` returns false. In Python 3, `\d` matches Unicode decimal digits by default. A validation regex that seems stricter in JS than in Python is often just using a narrower definition of 'digit'. If you mean ASCII, say `[0-9]` and remove the ambiguity.

Anchors and dotall are the quiet portability bugs

`.` does not match a newline unless you pass the `s` (dotAll) flag; Python needs `re.DOTALL` or an inline `(?s)`. More subtle is `$`. In JavaScript, `/abc$/` does not match `'abc\n'` — verified directly, it returns false. Perl, Python and PCRE-flavoured engines do let `$` match immediately before a trailing newline, so a pattern designed to tolerate a final line ending will silently fail when ported. With the `m` flag, `^` and `$` bind to line boundaries in both families, but the no-flag behaviour differs.

Line endings compound this. Files produced on Windows contain `\r\n`; a pattern written as `^.*$` with `m` will often leave a trailing `\r` inside the match. Normalise line endings before testing, or make the pattern explicit about `\r?\n`.

Backtracking can freeze the whole tab

JavaScript's regex engine is a backtracking engine, and it runs synchronously on the main thread. A pattern with nested quantifiers such as `(a+)+$` against a long string of `a`s followed by one `b` can require exponential work. There is no timeout, no match limit and no cancellation: the tab stops painting, stops responding to clicks, and the only remedy is to wait or close it. PCRE has backtrack limits, .NET offers a match timeout, and RE2-based engines guarantee linear time by construction. ECMAScript offers none of these.

  • Avoid nested quantifiers over the same character class. `(a+)+`, `(a|a)*` and `(\s*)*` are the usual offenders.
  • Rewrite with concrete anchors or a split. Often `[^,]+` or a simple `String.split` does the job in linear time.
  • Bound the input in any tool that lets a user supply both the pattern and the text. Short inputs make a bad pattern merely slow rather than fatal.
  • Run untrusted patterns in a Worker if you are building this into an application, so the UI thread stays responsive — though the Worker itself will still spin.

This is a real limitation of the browser-based tester, and it is worth stating plainly: it hands the pattern directly to `new RegExp` and calls `matchAll` on the text you supply. It is excellent for checking a pattern you mostly trust against a short sample. It is not a safe sandbox for hostile patterns or megabyte-sized inputs.

A porting checklist

  • Translate the flags first. `re.I` → `i`, `re.M` → `m`, `re.S` → `s`, and add `g` if you are using `matchAll`.
  • Add `u` whenever the pattern uses `\p{...}`, `\u{...}` or needs correct surrogate-pair handling.
  • Replace unsupported syntax: atomic groups and possessive quantifiers have no direct equivalent; simplify the pattern instead.
  • Reconcile named groups and check `groups` rather than numeric indices when porting from Python.
  • Test with a trailing newline, a CRLF pair, a non-ASCII letter and a non-ASCII digit. Those four inputs expose most cross-engine surprises.

For the surrounding workflow, the Text Trimmer is useful for normalising whitespace before a match, and the Duplicate Line Remover handles the line-oriented cleanup that people often try to force into a single regex. Splitting one clever pattern into two boring steps is usually faster, more portable and easier to debug.

Frequently asked questions

Why does the tester throw when I enter `i` as a flag? `matchAll` requires a global regex. Use `gi` instead.

Why does `\p{L}` not match accented letters? It needs the `u` flag — enter `gu`.

Can JavaScript do atomic groups or possessive quantifiers? No. Both raise `SyntaxError`. Rewrite the pattern to avoid ambiguous backtracking.

Does `$` match before a final newline in JavaScript? No, unlike Perl and Python. Normalise the input or use `m` with explicit line handling.

Is it safe to paste a regex from an untrusted source? Treat it like untrusted code: a catastrophic-backtracking pattern can freeze the tab. Keep the test text short, since everything runs locally in your browser with no server-side timeout.

The one-line version

A regex is not a portable string — it is a program compiled by a particular engine with particular flags. When one behaves differently, check the flag set and the feature list before you check the pattern.

Tools run privately in your browser

Every tool referenced in this guide processes your input in the browser rather than uploading it to a server we operate, and requires no account. A typical single job stays free. Larger batches, history export, and an ad-free page are optional on Pro. A few tools load a processing engine from a CDN on first use; see the privacy policy for details. Browse the full toolbox →

More from the blog