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 core pattern is exactly the same. Only the wrapping changes, plus one difference in
$(see below). - Python uses a raw string
r"...": backslashes are left as they are. Without ther, Python 3.12 printsSyntaxWarning: invalid escape sequence '\d'. - PHP puts the pattern inside a string, between delimiters: usually
/.../, but#...#or~...~work too. Flags go after the closing delimiter. - Go uses backticks
`...`, Go's raw string. In a double-quoted string"...", Go rejects\dat compile time.
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
re.findall()gives every match, likematch()withg. But when the pattern has a group, it returns the group's content:re.findall(r"([*_~])[^*_~]+\1", chat)gives['*', '*', '*']. Need the whole text?[m.group(0) for m in re.finditer(...)].re.match()only tries at the start of the text, as if there were a^. The chat starts with[, so the result isNone, even thoughPO-0412is on the first line.re.search()looks anywhere, andre.fullmatch()asks for the whole text to match.- The replacement text uses
\2-\1(or\g<2>), not$2-$1. The text"$2-$1"is written as it is: the result ison $2-$1. - A named group is written
(?P<day>...). The JavaScript style(?<day>...)is refused:re.error: unknown extension ?<d at position 4.
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)
- Delimiters are required. The last line forgets them, so PHP gives a Warning and
false. - PHP has no
gflag. "Every match" is a function of its own:preg_match_all(). Copying'/PO-\d{4}/g'from JavaScript givesWarning: preg_match_all(): Unknown modifier 'g'. - The results go into the third argument (
$m):$m[0]every whole match,$m[1]the content of group 1, and so on. Named groups are there too, in$t['day']. preg_replace()uses$1,$2like JavaScript. For a replacement function:preg_replace_callback().- The pattern is written in single quotes
'...', so\dreaches the regex whole.
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`
FindAllString(text, -1):-1means every match.MustCompilestops at once (panics) when the pattern is wrong;Compilereturns an error.- In the replacement text,
$2mo$1is read as a group named2mo, which doesn't exist, so the result ison 25. Use curly braces:${2}mo${1}. - Go follows the RE2 rules: no lookahead, no lookbehind, no backreference. A pattern that uses them is refused at compile time. Go reads
(?<as the start of a group name, hence the message "invalid named capture". Rewrite it: replace the lookbehind with a plain group,\$(\d+)and take group 1; replace the backreference with choices,\*[^*_~]+\*|_[^*_~]+_|~[^*_~]+~. - In return, Go's documentation guarantees a time linear in the length of the text. The ReDoS pattern
^(\w+\s?)+$from the previous lesson answersfalsefor 100,000 letters ending in!without hanging. - Named groups can be
(?P<name>...), and since Go 1.22 also(?<name>...).
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
- Python's
re.matchis locked to the start of the text. Usere.searchto look anywhere. re.findallwith a group returns the group's content, not the whole text.- A PHP pattern without delimiters, or with the
gflag.'PO-\d{4}'and'/PO-\d{4}/g'both end in a Warning. $1in Python is written as it is. Python uses\1.- Lookbehind or
\1taken to Go is refused at compile time. Rewrite it with a group or with|choices. - A pattern in an ordinary string.
"\d"makes Python print a SyntaxWarning and Go refuse to compile. User"..."in Python and backticks in Go.
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.