Readable Regex
Regexes have a reputation for being "write-only". This one-liner checks a semantic version number such as 1.4.0-beta.2:
^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-z-]+(?:\.[\da-z-]+)*))?$It works — but who can review it? This lesson shows techniques to keep patterns understandable.
1. Free-spacing (verbose) mode with comments
Python, Java, .NET, PCRE, Perl, Ruby and Rust support an x flag that ignores whitespace in the pattern and allows # comments. JavaScript does not, but the idea is worth knowing:
import re
SEMVER = re.compile(r"""
^
(?P<major>0|[1-9]\d*) \. # major: no leading zeros
(?P<minor>0|[1-9]\d*) \. # minor
(?P<patch>0|[1-9]\d*) # patch
(?: - (?P<pre>[\da-z-]+ (?:\.[\da-z-]+)* ) )? # optional pre-release
$
""", re.VERBOSE | re.IGNORECASE)
for v in ["1.4.0", "1.4.0-beta.2", "01.2.3", "1.2"]:
m = SEMVER.match(v)
print(v.ljust(13), m.groupdict() if m else "invalid")1.4.0 {'major': '1', 'minor': '4', 'patch': '0', 'pre': None}
1.4.0-beta.2 {'major': '1', 'minor': '4', 'patch': '0', 'pre': 'beta.2'}
01.2.3 invalid
1.2 invalid
In verbose mode a literal space must be escaped (\ ) or written as [ ], and a literal # as \#.
The same flag in other languages:
| Language | How to enable |
|---|---|
| Python | re.VERBOSE / re.X or (?x) |
| Java | Pattern.COMMENTS or (?x) |
| .NET | RegexOptions.IgnorePatternWhitespace or (?x) |
| PCRE / PHP / Perl / Ruby | /x modifier or (?x) |
Rust regex |
(?x) |
| JavaScript | not available — use the techniques below |
2. Build the pattern from named pieces
In JavaScript you can assemble a pattern from small, named strings with new RegExp(). Each piece can be read and tested on its own:
const num = String.raw`(?:0|[1-9]\d*)`;
const ident = String.raw`[\da-z-]+`;
const pre = String.raw`(?:-(?<pre>${ident}(?:\.${ident})*))?`;
const semver = new RegExp(
`^(?<major>${num})\\.(?<minor>${num})\\.(?<patch>${num})${pre}
Readable Regex - Regular Expressions · ExcelTAD
, "i"
);
for (const v of ["1.4.0", "1.4.0-beta.2", "01.2.3"]) {
const m = semver.exec(v);
console.log(v, m ? m.groups.pre ?? "(release)" : "invalid");
}1.4.0 (release)
1.4.0-beta.2 beta.2
01.2.3 invalid
Tip: A
String.rawtemplate keeps backslashes exactly as typed, so\dinside it reaches the regex engine as backslash-d. In a normal string literal you'd have to double it:"\\d".
3. Named groups instead of numbers
m.groups.major explains itself; m[1] doesn't. Combine with non-capturing groups for everything you don't read back.
4. Split the job between regex and code
A regex doesn't have to do everything. Matching a shape and checking a range in code is clearer than encoding the range into the pattern:
function isValidPort(s) {
return /^\d{1,5}$/.test(s) && Number(s) <= 65535;
}
console.log(["80", "8080", "65535", "65536", "x1"].map(isValidPort));[ true, true, true, false, false ]
Compare with the pure-regex alternative for 0–65535:
^(?:[0-9]{1,4}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$ — correct, but much harder to check.
5. Write tests next to the pattern
Keep a list of strings that must match and strings that must not. When someone changes the pattern, the list catches regressions:
const slug = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const good = ["hello", "hello-world", "a1-b2-c3"];
const bad = ["Hello", "-start", "end-", "double--dash", ""];
console.log(good.every((s) => slug.test(s)), bad.some((s) => slug.test(s)));true false
6. Test visually
Paste realistic samples into a tester — like the one in this course — and look at exactly what matched:
/^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)$/gm
1.4.0
10.20.30
1.04.02 matches
#1 "1.4.0" at index 0
group major: "1"
group minor: "4"
group patch: "0"
#2 "10.20.30" at index 6
group major: "10"
group minor: "20"
group patch: "30"
Test yourself
What does the x (verbose) flag allow?
- Extended Unicode
- Whitespace and
#comments inside the pattern - Extra-fast matching
- Exact matches only
Does JavaScript support the x flag?
- Yes, since ES2015
- No — build patterns from pieces with
new RegExp()instead - Only with
u - Only in Node