regex
creates readable, high performance, native JavaScript regular expressions with advanced features and best practices built-in. It's lightweight (6.5 KB minified and brotlied) and supports all ES2024+ regex functionality. It can also be used dependency-free as a Babel plugin.
Highlights include support for free spacing and comments, atomic groups via (?>…)
which can help you avoid ReDoS, subroutines via \g<name>
which enable powerful composition, and context-aware interpolation of RegExp
instances, escaped strings, and partial patterns.
With the regex
package, JavaScript steps up as one of the best regex flavors alongside PCRE and Perl, and maybe surpassing C++, Java, .NET, and Python.
\\\\
since it's a raw string template tag.(?>…)
can dramatically improve performance and prevent ReDoS.\g<name>
enable powerful composition, improving readability and maintainability.import {regex, partial} from 'regex';
// Subroutines
const record = regex('gm')`^
Born: (?<date> \d{4}-\d{2}-\d{2} ) \n
Admitted: \g<date> \n
Released: \g<date>
$`;
// Atomic groups; avoid ReDoS from the nested, overlapping quantifier
const words = regex`^(?>\w+\s?)+$`;
// Context-aware and safe interpolation
const re = regex('m')`
# Only the inner regex is case insensitive (flag i)
# Also, the outer regex's flag m is not applied to it
${/^a.b$/i}
|
# Strings are contextually escaped and repeated as complete units
^ ${'a.b'}+ $
|
# This string is contextually sandboxed but not escaped
${partial('^ a.b $')}
`;
// Adjusts backreferences in interpolated regexes
regex`^ ${/(dog)\1/} ${/(cat)\1/} $`;
// → /^(dog)\1(cat)\2$/v
npm install regex
import {regex, partial} from 'regex';
In browsers:
<script src="https://cdn.jsdelivr.net/npm/regex/dist/regex.min.js"></script>
<script>
const {regex, partial} = Regex;
</script>
Due to years of legacy and backward compatibility, regular expression syntax in JavaScript is a bit of a mess. There are four different sets of incompatible syntax and behavior rules that might apply to your regexes depending on the flags and features you use. The differences are just plain hard to fully grok and can easily create subtle bugs.
Additionally, JavaScript regex syntax is hard to write and even harder to read and refactor. But it doesn't have to be that way! With a few key features — raw multiline strings, insignificant whitespace, comments, subroutines, interpolation, and named capture only mode — even long and complex regexes can be beautiful, grammatical, and easy to understand.
regex
adds all of these features and returns native RegExp
instances. It always uses flag v (already a best practice for new regexes) so you never forget to turn it on and don't have to worry about the differences in other parsing modes (and, in environments without native flag v, it enforces v's rules so your regexes are forward and backward compatible). It supports atomic groups via (?>…)
to help you improve the performance of your regexes and avoid catastrophic backtracking. And it gives you best-in-class, context-aware interpolation of RegExp
instances, escaped strings, and partial patterns.
Historically, JavaScript regexes were not as powerful or readable as other major regex flavors like PCRE, Perl, C++, Java, .NET, and Python. With recent advancements and the regex
package, those days are over. Modern JavaScript regexes have significantly improved (adding lookbehind, named capture, Unicode properties, character class subtraction and intersection, etc.). The regex
package, with its extended syntax and implicit flags, adds the key remaining pieces needed to stand alongside or surpass other major flavors.
Atomic groups, written as (?>…)
, automatically throw away all backtracking positions remembered by any tokens inside the group. They're most commonly used to improve performance, and are a much needed feature that regex
brings to native JavaScript regular expressions.
Example:
regex`^(?>\w+\s?)+$`
This matches strings that contain word characters separated by spaces, with the final space being optional. Thanks to the atomic group, it instantly fails to find a match if given a long list of words that end with something not allowed, like 'A target string that takes a long time or can even hang your browser!'
.
Try running this without the atomic group (as /^(?:\w+\s?)+$/
) and, due to the exponential backtracking triggered by the many ways to divide the work of the inner and outer +
quantifiers, it will either take a very long time, hang your browser/server, or throw an internal error after a delay. This is called catastrophic backtracking or ReDoS, and it has taken down major services like Cloudflare and Stack Overflow. regex
and atomic groups to the rescue!
[!NOTE] Atomic groups are based on the JavaScript proposal for them as well as support in many other regex flavors.
Subroutines are written as \g<name>
(where name refers to a named group), and they treat the referenced group as an independent subpattern that they try to match at the current position. This enables subpattern composition and reuse, which improves readability and maintainability.
The following example illustrates how subroutines and backreferences differ:
// A backreference with \k<name>
regex`(?<prefix>sens|respons)e\ and\ \k<prefix>ibility`
/* Matches: - 'sense and sensibility'
- 'response and responsibility' */
// A subroutine with \g<name>
regex`(?<prefix>sens|respons)e\ and\ \g<prefix>ibility`
/* Matches: - 'sense and sensibility'
- 'sense and responsibility'
- 'response and sensibility'
- 'response and responsibility' */
Subroutines go beyond the composition benefits of interpolation. Apart from the obvious difference that they don't require variables to be defined outside of the regex, they also don't simply insert the referenced subpattern.
To illustrate points 2 and 3, consider:
regex`(?<double> (?<char>.) \k<char> ) \g<double> \k<double>`
// The backreference \k<double> matches whatever was matched by capturing group
// `double`, regardless of what was matched by the subroutine. For example, the
// regex matches 'xx!!xx' but not 'xx!!!!'
You can also define subpatterns for use by reference only:
// Matches an IPv4 address such as '192.168.12.123'
regex`\b \g<byte> (\.\g<byte>){3} \b
# The {0} quantifier allows defining a subpattern without matching it
(?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d ){0}
`
// Matches a record with several date fields and captures each value
regex`
^ Name:\ (?<name>.*) \n
Born:\ (?<born> \g<date>) \n
Admitted:\ (?<admitted>\g<date>) \n
Released:\ (?<released>\g<date>) $
# Define subpatterns
( (?<date> \g<year>-\g<month>-\g<day>)
(?<year> \d{4})
(?<month> \d{2})
(?<day> \d{2})
){0}
`
[!NOTE] Subroutines are based on the feature in PCRE and Perl. PCRE allows several syntax options including
\g<name>
, whereas Perl uses(?&name)
. Ruby also supports subroutines (and uses the\g<name>
syntax), but it has behavior differences that make its subroutines not always act as independent subpatterns.
You can use the regex
extension package regex-recursion
to match recursive patterns via (?R)
and \g<name>
, up to a specified max depth.
Flags are added like this:
regex('gm')`^.+`
RegExp
instances interpolated into the pattern preserve their own flags locally (see Interpolating regexes).
Flag v and emulated flags x and n are always on when using regex
, giving your regexes a modern baseline syntax and avoiding the need to continually opt-in to their superior modes.
v
JavaScript's native flag v gives you the best level of Unicode support, strict errors, and all the latest regex features like character class set operations and properties of strings (see MDN). It's always on when using regex
, which helps avoid numerous Unicode-related bugs, and means there's only one way to parse a regex instead of four (so you only need to remember one set of regex syntax and behavior).
Flag v is applied to the full pattern after interpolation happens.
In environments without native support for flag v, flag u is automatically used instead while still enforcing flag v's rules. So your regexes are forward and backward compatible.
x
Emulated flag x makes whitespace insignificant and adds support for line comments (starting with #
), allowing you to freely format your regexes for readability. It's always implicitly on, though it doesn't extend into interpolated RegExp
instances (to avoid changing their meaning).
Example:
const re = regex`
# Match a date in YYYY-MM-DD format
(?<year> \d{4} ) - # Year part
(?<month> \d{2} ) - # Month part
(?<day> \d{2} ) # Day part
# Escape whitespace and hashes to match them literally
\ # space char
\x20 # space char
\# # hash char
\s # any whitespace char
# Since embedded strings are always matched literally, you can also match
# whitespace by embedding it as a string
${' '}+
# Partials are directly embedded, so they use free spacing
${partial`\d + | [a - z]`}
# Interpolated regexes use their own flags, so they preserve their whitespace
${/^Hakuna matata$/m}
`;
[!NOTE] Flag x is based on the JavaScript proposal for it as well as support in many other regex flavors. Note that the rules for whitespace within character classes are inconsistent across regex flavors, so
regex
follows the JavaScript proposal and the flag xx option from Perl and PCRE.
n
Emulated flag n gives you named capture only mode, which prevents the grouping metacharacters (…)
from capturing. It's always implicitly on, though it doesn't extend into interpolated RegExp
instances (to avoid changing their meaning).
Requiring the syntactically clumsy (?:…)
where you could just use (…)
hurts readability and encourages adding unneeded captures (which hurt efficiency and refactoring). Flag n fixes this, making your regexes more readable.
Example:
// Doesn't capture
regex`\b(ab|cd)\b`
// Use standard (?<name>…) to capture as `name`
[!NOTE] Flag n is based on .NET, C++, PCRE, Perl, and XRegExp, which share the n flag letter but call it explicit capture, no auto capture, or nosubs. In
regex
, the implicit flag n also prevents using numbered backreferences to refer to named groups in the outer regex, which follows the behavior of C++ (Ruby also always prevents this, despite not having flag n). Referring to named groups by number is a footgun, and the way that named groups are numbered is inconsistent across regex flavors.Aside: Flag n's behavior also enables
regex
to emulate atomic groups, subroutines, and recursion.
The meaning of flags (or their absense) on interpolated regexes is preserved. For example, with flag i (ignoreCase
):
regex`hello-${/world/i}`
// Matches 'hello-WORLD' but not 'HELLO-WORLD'
regex('i')`hello-${/world/}`
// Matches 'HELLO-world' but not 'HELLO-WORLD'
This is also true for other flags that can change how an inner regex is matched: m
(multiline
) and s
(dotAll
).
As with all interpolation in
regex
, embedded regexes are sandboxed and treated as complete units. For example, a following quantifier repeats the entire embedded regex rather than just its last token, and top-level alternation in the embedded regex will not break out to affect the meaning of the outer regex. Numbered backreferences are adjusted to work within the overall pattern.
regex
escapes special characters in interpolated strings (and values coerced to strings). This escaping is done in a context-aware and safe way that prevents changing the meaning or error status of characters outside the interpolated string.
As with all interpolation in
regex
, escaped strings are sandboxed and treated as complete units. For example, a following quantifier repeats the entire escaped string rather than just its last character. And if interpolating into a character class, the escaped string is treated as a flag-v-mode nested union if it contains more than one character node.
As a result, regex
is a safe and context-aware alternative to JavaScript proposal RegExp.escape
.
// Instead of
RegExp.escape(str)
// You can say
regex`${str}`.source
// Instead of
new RegExp(`^(?:${RegExp.escape(str)})+$`)
// You can say
regex`^${str}+$`
// Instead of
new RegExp(`[a-${RegExp.escape(str)}]`, 'u') // Flag u/v required to avoid bugs
// You can say
regex`[a-${str}]`
// Given the context at the end of a range, throws if more than one char in str
// Instead of
new RegExp(`[\\w--[${RegExp.escape(str)}]]`, 'v')
// You can say
regex`[\w--${str}]`
Some examples of where context awareness comes into play:
~
is not escaped at the top level, but it must be escaped within character classes in case it's immediately followed by another ~
(in or outside of the interpolation) which would turn it into a reserved UnicodeSets double punctuator.\0
, else RegExp
throws (or in Unicode-unaware mode they might turn into octal escapes).A
-Z
and a
-z
must be escaped if preceded by uncompleted token \c
, else they'll convert what should be an error into a valid token that probably doesn't match what you expect.\
. Doing nothing could turn e.g. w
into \w
and introduce a bug, but then escaping the first character wouldn't prevent the \
from mangling it, and if you escaped the preceding \
elsewhere in your code you'd change its meaning.These and other issues (including the effects of current and potential future flags like x) make escaping without context unsafe to use at arbitrary positions in a regex, or at least complicated to get right. The existing popular regex escaping libraries don't even attempt to handle these kinds of issues.
regex
solves all of this via context awareness. So instead of remembering anything above, you should just switch to always safely escaping regex syntax via regex
.
As an alternative to interpolating RegExp
instances, you might sometimes want to interpolate partial regex patterns as strings. Some example use cases:
RegExp
instances since their top-level syntax context doesn't match).RegExp
).For all of these cases, you can interpolate partial(str)
to avoid escaping special characters in the string or creating an intermediary RegExp
instance. You can also use partial`…`
as a tag, as shorthand for partial(String.raw`…`)
.
Apart from edge cases, partial
just embeds the provided string or other value directly. But because it handles the edge cases, partial patterns can safely be interpolated anywhere in a regex without worrying about their meaning being changed by (or making unintended changes in meaning to) the surrounding pattern.
As with all interpolation in
regex
, partials are sandboxed and treated as complete units. This is relevant e.g. if a partial is followed by a quantifier, if it contains top-level alternation, or if it's bordered by a character class range or set operator.
If you want to understand the handling of partial patterns more deeply, let's look at some edge cases…
The above descriptions of interpolation might feel complex. But there are three simple rules that guide the behavior in all cases:
Examples where rule #3 is relevant: With following quantifiers, if they contain top-level alternation or unnamed backreferences, or if they're placed in a character class range or set operation.
Context | Example | String / coerced | Partial pattern | RegExp |
---|---|---|---|---|
Default |
regex`${'^.+'}` |
• Sandboxed • Atomized • Escaped |
• Sandboxed • Atomized |
• Sandboxed • Atomized • Backrefs adjusted • Flags localized |
Character class: […] , [^…] , [[…]] , etc. |
regex`[${'a-z'}]` |
• Sandboxed • Atomized • Escaped |
• Sandboxed • Atomized |
Error |
Interval quantifier: {…} |
regex`.{1,${5}}` |
• Sandboxed • Escaped |
• Sandboxed |
Error |
Enclosed token: \p{…} , \P{…} , \u{…} , [\q{…}] |
regex`\u{${'A0'}}` |
|||
Group name: (?<…>) , \k<…> , \g<…> |
regex`…\k<${'a'}>` |
${x}*
matches any number of the value specified by x
, and not just its last token. In character class context, subtraction and intersection operators apply to the entire atom.a
or \u0061
) can be interpolated at these positions.The implementation details vary for how
regex
accomplishes sandboxing and atomization, based on the details of the specific pattern. But the concepts should always hold up.
regex
transpiles its input to native RegExp
instances. Therefore regexes created by regex
perform equally fast as native regular expressions. regex
calls can also be transpiled via a Babel plugin, avoiding the tiny overhead of transpiling at runtime.
For regexes that rely on or have the potential to trigger heavy backtracking, you can dramatically improve beyond native performance via the atomic groups feature built into regex
.
regex
uses flag v (unicodeSets
) when it's supported natively. Flag v is supported by 2023-era browsers (compat table) and Node.js 20+. When v isn't available, flag u is automatically used instead (while still enforcing v's rules), which extends support to Node.js 12+ and 2019-era browsers (2017-era with a build step that transpiles private class fields and the string matchAll
method).
The following edge cases rely on modern JavaScript features:
regex
uses nested character classes (which require native flag v) when interpolating more than one token at a time inside character classes. A descriptive error is thrown when this isn't supported, which you can avoid by not interpolating multi-token partials/strings into character classes.RegExp
instance with a different value for flag i than its outer regex relies on regex modifiers, a bleeding-edge feature available in Chrome, Edge, and Opera 125+. A descriptive error is thrown in environments without support, which you can avoid by aligning the use of flag i on inner and outer regexes. Local-only application of other flags doesn't rely on this feature.regex
support extensions?regex
was partly inspired by XRegExp
.tag
and regexp-make-js. regex
's only dependency is the ultra-lightweight regex-utilities
, which was separated so it can be reused by regex
extensions.
Crafted by Steven Levithan with ❤︎ for regular expressions and their enthusiasts.
MIT License.