Regex Across Languages

The pattern is the same, the wrapping differs: JavaScript /pattern/flags, Python r"pattern" with the re functions, PHP '/pattern/flags' with required…

Regex isn't only in JavaScript. Python, PHP and Go have it too, and the patterns are almost the same. What differs: how the pattern is wrapped, the names of the functions, and which features exist. Picture Mrs. Ratna's tart recipe taken to three kitchens. The recipe is the same, but each kitchen turns its oven on its own way, and one kitchen has a rule: no recipe that could burn is allowed in. The recipe is the pattern, the kitchen is the language, and the kitchen that turns down risky recipes is Go: it has no lookaround and no backreference, and in exchange it is guaranteed never to fall into ReDoS. Every output in this lesson comes from really running the code: Python 3.12, PHP 8.4 and Go 1.27 (on the Go Playground).

Same pattern, different wrapping

The date-check pattern ^(\d{4})-(\d{2})-(\d{2})$ in four languages:

Language How it's written Flags, e.g. ignore case
JavaScript /^(\d{4})-(\d{2})-(\d{2})$/.test(date) after the slash: /.../i
Python re.match(r"^(\d{4})-(\d{2})-(\d{2})$", date) an argument: re.I
PHP preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date) after the delimiter: '/.../i'
Go regexp.MustCompile(`^(\d{4})-(\d{2})-(\d{2})$`) inside the pattern: (?i)

The result is the same in all three: ('2026', '03', '25') in Python, int(1) from preg_match in PHP, and [2026-03-25 2026 03 25] from FindStringSubmatch in Go.

One difference is easy to miss: in Python and PHP, $ also matches just before a final \n, so "2026-03-25\n" passes too. JavaScript and Go answer false. To lock the end of the text, use re.fullmatch() or \Z in Python, and \z or the D modifier in PHP. Since Python 3.14, \z works in Python too.

A second difference: in Python, \d and \w know the digits and letters of every language (Unicode). The date pattern above lets "٢٠٢٦-٠٣-٢٥" (Arabic digits) pass, and re.findall(r"\b\w+\b", "café ok") gives ['café', 'ok']. In JavaScript and Go, \d is only 0 to 9 and \w only A-Z, a-z, 0-9 and _, so that date is refused and the result is caf and ok. PHP works like JavaScript, unless the pattern has the u flag. When a Python validator must accept only 0 to 9, add re.ASCII (re.match(pattern, date, re.ASCII) gives None) or write [0-9].

A third difference: a lookbehind in Python must have a fixed width. (?<=\$|USD )\d+ works in JavaScript and PHP (5000 and 7000 from "USD 5000 and $7000"), but Python refuses it with look-behind requires fixed-width pattern, because $ is 1 character and USD is 4. In Python, split it into two lookbehinds, (?:(?<=\$)|(?<=USD ))\d+, or use a plain group (?:\$|USD )(\d+) and take group 1.

Python: the re module

import re
chat = open("chat.txt").read()  # the 6 lines of the Ratna's Kitchen PO chat

print(re.findall(r"PO-\d{4}", chat))
print(re.match(r"PO-\d{4}", chat))
print(re.search(r"PO-\d{4}", chat))
print(re.sub(r"(\d{2})/(\d{2})", r"\2-\1", "on 25/03"))
m = re.search(r"on (?P<day>\d{2})/(?P<month>\d{2})", chat)
print(m.group("day"), m.group("month"))
['PO-0412', 'PO-0413']
None
<re.Match object; span=(126, 133), match='PO-0412'>
on 03-25
25 03

PHP: the preg_* functions

<?php
$chat = file_get_contents('chat.txt'); // the 6 lines of the Ratna's Kitchen PO chat

preg_match_all('/PO-\d{4}/', $chat, $m);
print_r($m[0]);
echo preg_replace('/(\d{2})\/(\d{2})/', '$2-$1', 'on 25/03'), "\n";
preg_match('/on (?<day>\d{2})\/(?<month>\d{2})/', $chat, $t);
echo $t['day'], ' ', $t['month'], "\n";
var_dump(preg_match('PO-\d{4}', $chat));
Array
(
    [0] => PO-0412
    [1] => PO-0413
)
on 03-25
25 03

Warning: preg_match(): Delimiter must not be alphanumeric, backslash, or NUL byte in …/po.php on line 9
bool(false)

Go: the regexp package (RE2)

re := regexp.MustCompile(`PO-\d{4}`)
fmt.Println(re.FindAllString(chat, -1))

date := regexp.MustCompile(`(\d{2})/(\d{2})`)
fmt.Println(date.ReplaceAllString("on 25/03", "${2}-${1}"))
fmt.Println(date.ReplaceAllString("on 25/03", "$2mo$1"))

_, err := regexp.Compile(`(?<=\$)\d+`)
fmt.Println(err)
_, err = regexp.Compile(`([*_~])[^*_~]+\1`)
fmt.Println(err)
[PO-0412 PO-0413]
on 03-25
on 25
error parsing regexp: invalid named capture: `(?<=\$)\d+`
error parsing regexp: invalid escape sequence: `\1`

Feature table

Feature JavaScript Python re PHP preg_* Go regexp
Lookahead and lookbehind yes yes (fixed-width lookbehind) yes no
Backreference \1 yes yes yes no
Named group (?<n>...) (?P<n>...) both both
Replacement text $1 \1 $1 ${1}
Every match match(/.../g) findall() preg_match_all() FindAllString(s, -1)
Time guaranteed linear no no no yes
A strict end of text $ \Z or fullmatch() \z or the D modifier $
\d and \w ASCII Unicode (ASCII with re.ASCII) ASCII (Unicode with the u flag) ASCII

⚠️ JavaScript habits that break in other languages

TL;DR: The pattern is the same, the wrapping differs: JavaScript /pattern/flags, Python r"pattern" with the re functions, PHP '/pattern/flags' with required delimiters (/, # or ~) and the preg_* functions, Go `pattern` with the regexp package. In Python, re.match is locked to the start of the text (a chat that starts with [ gives None), while re.search looks anywhere. PHP has no g flag: use preg_match_all(). The replacement text is $1 in JavaScript and PHP, \1 in Python, ${1} in Go. Go uses RE2: no lookaround and no backreference, but its time is guaranteed linear, so it is immune to ReDoS.

⚡ The same pattern, a different wrapping

Meaning: The core pattern ^(\d{4})-(\d{2})-(\d{2})$ is exactly the same in all four languages. One difference: $ in Python and PHP still accepts a \n at the end (lock it with \Z or \z). Only the wrapping changes: JavaScript /pattern/flags, Python r"pattern", PHP '/pattern/flags', Go `pattern`.

⚡ PHP needs delimiters

Write:

preg_match_all('/PO-\d{4}/', $chat, $m);
print_r($m[0]);
Guess first: what does preg_match('PO-\d{4}', $chat) give, with no slashes?

A Warning (Delimiter must not be alphanumeric, backslash, or NUL byte) and false. PHP puts the pattern inside a string between delimiters, usually /.../, or #...# and ~...~.

Meaning: PHP has no g flag either: every match is a function of its own, preg_match_all().

⚡ Python's re.match is locked to the start

Write:

print(re.match(r"PO-\d{4}", chat))   # None
print(re.search(r"PO-\d{4}", chat))  # <re.Match object; span=(126, 133), match='PO-0412'>

Meaning: The chat starts with [, so re.match gives None. re.search looks anywhere. And Go refuses lookaround and \1 at compile time, in exchange for a time that is guaranteed linear.

What you will learn