How to Convert a JavaScript Regex to Python
Published · 5 min read
A pattern that works in the browser often needs to run on a Python backend too: the same email check in a form and in an API, or the same log filter in a dashboard and in a script. Most of the syntax carries over unchanged, which is exactly why the differences are easy to miss. A converted pattern usually compiles without complaint and then quietly matches something slightly different. This guide walks through every difference that matters in practice, with side-by-side code, and ends with a short checklist for testing the result.
What stays the same
Both languages use a backtracking engine with a very similar core syntax. Character classes like [a-z], shorthand classes \d, \w and \s, quantifiers including counted ones such as {2,4}, lazy quantifiers like +?, alternation with |, non-capturing groups (?:...), lookahead (?=...) and (?!...), and numbered backreferences like \1 all behave the same way for ordinary ASCII text. If your pattern only uses these pieces, the main work is moving it out of a JavaScript literal and into a Python string.
That move is the first trap. In JavaScript you usually write a literal like /\d+/g, where the slashes are delimiters and the flags follow. In Python a pattern is an ordinary string, so always use a raw string, r"\d+". Without the r prefix, Python processes the backslashes itself before the regex engine sees them, which turns \b into a backspace character. You also no longer need to escape forward slashes, because they are not delimiters in Python.
import re
# JavaScript: const re = /\bINV-\d{6}\b/g;
pattern = re.compile(r"\bINV-\d{6}\b")
text = "Paid INV-004211 and INV-004212; INV-42 is a typo."
print(pattern.findall(text)) # ['INV-004211', 'INV-004212']Flags become constants or function choices
JavaScript puts flags after the closing slash. Python passes them as constants to re.compile or the search function, combined with |. Most map directly, but two JavaScript flags have no flag equivalent at all, because Python expresses the same idea by choosing a different function.
ibecomesre.IGNORECASE,mbecomesre.MULTILINEandsbecomesre.DOTALL.ghas no flag. Usefindallorfinditerto get every match andsubto replace every match;searchreturns only the first.uis unnecessary, because Python string patterns are Unicode-aware by default. That default changes how\dand\wbehave, as the next section explains.y(sticky) has no flag. A compiled pattern'smatch(text, pos)method anchors the attempt at a given position instead.
The function you pick also replaces anchors you might have relied on. re.search behaves like JavaScript's test, looking anywhere in the string. re.match only tries at the start. re.fullmatch requires the whole string to match, which is usually what you want for validation. The flags lesson covers what each flag does in more detail.
Named groups and replacements
Named groups are the difference most likely to stop a converted pattern from compiling. JavaScript writes (?<year>\d{4}). Python's re module requires a P: (?P<year>\d{4}). Backreferences to a named group change too, from \k<year> in JavaScript to (?P=year) in Python.
Replacement strings use different syntax again. JavaScript refers to groups as $1 and $<year> and writes a literal dollar sign as $$. Python uses \1 or \g<1> for numbered groups and \g<year> for named ones, and a dollar sign is just a dollar sign. Prefer \g<1> when a digit follows the reference, because \10 is read as group ten. The named groups and replace with groups lessons explain both ideas with exercises.
// JavaScript
const iso = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/g;
"Due 2026-12-03".replace(iso, "$<day>/$<month>/$<year>"); // "Due 03/12/2026"# Python
iso = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})")
iso.sub(r"\g<day>/\g<month>/\g<year>", "Due 2026-12-03") # 'Due 03/12/2026'
m = iso.search("Due 2026-12-03")
print(m.group("year"), m.groupdict()) # 2026 {'year': '2026', ...}Three silent differences that change results
The changes above produce errors or obviously wrong output, so you notice them. The next three are more dangerous: the pattern runs, the tests you thought of pass, and edge cases behave differently.
Dollar sign before a final newline
In JavaScript, $ without the m flag matches only at the very end of the string. In Python it also matches just before a newline at the end. So ^\d+$ accepts "123\n" in Python but rejects it in JavaScript. For validation, use re.fullmatch or end the pattern with \Z, which means the absolute end in Python. JavaScript has no \Z, so this is one place where the Python version should be written differently on purpose.
Digits and word characters beyond ASCII
JavaScript's \d matches only 0 to 9, even with the u flag. Python's \d matches any Unicode decimal digit, including Arabic-Indic and Devanagari digits, and \w matches letters from every script. A form that rejects ٣٤٥ in the browser may accept it on the server. If you need the JavaScript behaviour, add re.ASCII or write [0-9] explicitly. The Unicode text lesson shows why this matters for names and numbers.
Unicode property escapes
Modern JavaScript supports \p{L} for any letter when the u flag is on. Python's built-in re module does not support \p{...} at all and raises an error. Either rewrite the class, often as [^\W\d_] for letters, or use the third-party regex module, which understands property escapes.
Lookbehind and other features that may not convert
JavaScript allows lookbehind of any length, so (?<=Total:\s*)\d+ is valid. Python's re requires every lookbehind to have a fixed width and rejects that pattern with "look-behind requires fixed-width pattern". The usual fix is to match the prefix normally and capture the part you want: Total:\s*(\d+), then read group 1. The lookbehind lesson covers this workaround.
A few other JavaScript-only pieces need small rewrites. [^] (any character including newlines) becomes . with re.DOTALL, or [\s\S]. Code point escapes like \u{1F600} become \U0001F600 in a Python string. The reverse direction has its own list, since Python 3.11 added atomic groups and possessive quantifiers that JavaScript lacks. The article on regex differences between languages compares all eight languages RegexLab supports.
A conversion checklist
Run through these steps for every pattern you move from JavaScript to Python:
- Copy the pattern into a raw string
r"..."and drop the slashes and any escaped forward slashes. - Translate the flags, and replace
gwithfindall,finditerorsub. - Change
(?<name>to(?P<name>and\k<name>to(?P=name). - Rewrite replacement strings:
$1to\g<1>,$<name>to\g<name>,$$to$. - For validation, use
re.fullmatchor\Zinstead of trusting$. - Decide whether
\dand\wshould be ASCII-only, and addre.ASCIIif so. - Replace
\p{...}classes and variable-length lookbehind. - Run the same list of should-match and should-not-match strings in both languages and compare.
The last step is the one that catches real bugs. Keep a small table of test strings next to the pattern, including an empty string, a value with a trailing newline, and a value with non-ASCII digits. If both versions agree on all of them, the conversion is done. If you want ready-made patterns to start from, the pattern library has 150 tested patterns with code for Python, JavaScript and six other languages.
Frequently asked questions
- Can I paste a JavaScript regex straight into Python?
- Often yes for simple patterns, as long as you use a raw string. Named groups, flags, replacement strings, Unicode property escapes and variable-length lookbehind all need changes, and $ behaves differently before a final newline.
- Why does my named group fail in Python?
- Python's re module requires the P syntax: (?P<name>...) instead of (?<name>...), and (?P=name) instead of \k<name> for a backreference.
- What is the Python equivalent of the g flag?
- There is no flag. Use re.findall or re.finditer to get all matches and re.sub to replace all of them; re.search returns only the first match.
- Does \d mean the same thing in JavaScript and Python?
- Not exactly. JavaScript's \d matches only 0-9. Python's \d matches any Unicode decimal digit unless you add re.ASCII or write [0-9].
Related posts
- Regex for Beginners: A Practical IntroductionLearn regex from scratch: literals, character sets, quantifiers, anchors, groups and flags, with small tested examples in JavaScript and Python.
- Regex vs AI: When to Use WhichRegex vs AI for text tasks: determinism, cost, privacy and speed versus flexibility, and how to combine the two safely in real projects.
- How to Clean Messy Data with RegexPractical regex find-and-replace recipes for messy data: whitespace, duplicate words and lines, dates, phone numbers, leftover HTML and CSV fields.