regex is a template tag that extends JavaScript regular expressions with features from other leading regex libraries that make regexes more powerful and dramatically more readable. It returns native RegExp instances that run with native performance, and can exceed the performance of regex literals you'd write yourself. It's also lightweight, has no dependencies, supports all ES2025 regex features, has built-in TypeScript declarations, and can be used as a Babel plugin to avoid any runtime dependencies or user runtime cost.
Highlights include support for free spacing and comments, atomic groups via (?>…) that can help you avoid ReDoS, subroutines via \g<name> and subroutine definition groups via (?(DEFINE)…) that enable powerful subpattern composition, and context-aware interpolation of regexes, escaped strings, and partial patterns.
With the regex library, JavaScript steps up as one of the best regex flavors alongside PCRE and Perl, possibly surpassing C++, Java, .NET, Python, and Ruby.
\\\\ since it's a raw string template tag.(?>…) can dramatically improve performance and prevent ReDoS.\g<name> enable powerful composition, improving readability and maintainability.(?(DEFINE)…) allow groups within them to be used by reference only.import {regex, pattern} from 'regex'; // Subroutines and subroutine definition group const record = regex` ^ Admitted:\ (?<admitted> \g<date>) \n Released:\ (?<released> \g<date>) $ (?(DEFINE) (?<date> \g<year>-\g<month>-\g<day>) (?<year> \d{4}) (?<month> \d{2}) (?<day> \d{2}) ) `; // Atomic group: Avoids 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 ${pattern('^ a.b $')} `; // Numbered backreferences in interpolated regexes are adjusted const double = /(.)\1/; regex`^ (?<first>.) ${double} ${double} $`; // → /^(?<first>.)(.)\2(.)\3$/v
npm install regex
import {regex, pattern} from 'regex';
In browsers:
<details> <summary>Using a global name (no import)</summary><script type="module"> import {regex, pattern} from 'https://cdn.jsdelivr.net/npm/regex@4.0.0/+esm'; // … </script>
</details><script src="https://cdn.jsdelivr.net/npm/regex@4.0.0/dist/regex.min.js"></script> <script> const {regex, pattern} = 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.
<details> <summary>See the four parsing modes</summary>\k when a named capture appears anywhere in a regex.\W, character class ranges, and quantifiers), changes flag <kbd>i</kbd> to apply Unicode case-folding, and adds support for new syntax.\p and \P within negated [^…], and adds support for new features/syntax.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, definition groups, 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 <kbd>v</kbd> (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 (in environments without native <kbd>v</kbd>, flag <kbd>u</kbd> is automatically used instead while applying <kbd>v</kbd>'s escaping rules so your regexes are forward and backward compatible). It also 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 Java, .NET, PCRE, Perl, Python, and Ruby. With recent advancements and the regex library, those days are over. Modern JavaScript regexes have significantly improved (adding lookbehind, named capture, Unicode properties, character class subtraction and intersection, etc.). The regex library, with its extended syntax and implicit flags, adds the key remaining pieces needed to stand alongside or surpass other major flavors.
Atomic groups are noncapturing groups with special behavior, and are written as (?>…). After matching the contents of an atomic group, the regex engine automatically throws away all backtracking positions remembered by any tokens within the group. Atomic groups are 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!
Consider regex`(?>a+)ab` vs regex`(a+)ab`. The former (with an atomic group) doesn't match 'aaaab', but the latter does. The former doesn't match because:
a+ within the atomic group to match all the as in the target string.a outside the group, it fails (the next character in the target string is a b), so the regex engine backtracks.+ give up its last matched a, there are no additional options to try and the overall match attempt fails.For a more useful example, consider how this can affect lazy (non-greedy) quantifiers. Let's say you want to match <b>…</b> tags that are followed by !. You might try this:
const re = regex('gis')`<b>.*?</b>!`; // This is OK '<b>Hi</b>! <b>Bye</b>.'.match(re); // → ['<b>Hi</b>!'] // But not this '<b>Hi</b>. <b>Bye</b>!'.match(re); // → ['<b>Hi</b>. <b>Bye</b>!'] 👎
What happened with the second string was that, when an ! wasn't found immediately following the first </b>, the regex engine backtracked and expanded the lazy .*? to match an additional character (in this case, the < of the </b> tag) and then continued onward, all the way to just before the </b>! at the end.
You can prevent this by wrapping the lazily quantified token and its following delimiter in an atomic group, as follows:
const re = regex('gis')`<b>(?>.*?</b>)!`; '<b>Hi</b>. <b>Bye</b>!'.match(re); // → ['<b>Bye</b>!'] 👍
Now, after the regex engine finds the first </b> and exits the atomic group, it can no longer backtrack into the group and change what the .*? already matched. As a result, the match attempt fails at the beginning of this example string. The regex engine then moves on and starts over at subsequent positions in the string, eventually finding <b>Bye</b>!. Success.
[!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 in between by the subroutine \g<double>. For example, this regex matches 'xx!!xx', but not 'xx!!!!'.
regex, subroutines are applied after interpolation, giving them maximal flexibility.The following regex matches an IPv4 address such as "192.168.12.123":
const ipv4 = regex` \b \g<byte> (\.\g<byte>){3} \b # Define the 'byte' subpattern (?<byte> 2[0-4]\d | 25[0-5] | 1\d\d | [1-9]?\d ){0} `;
Above, the {0} quantifier at the end of the (?<byte>…) group allows defining the group without matching it at that position. The subpattern within it can then be used by reference elsewhere within the pattern.
This next regex matches a record with multiple date fields, and captures each value:
const record = regex` ^ 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} `;
Here, the {0} quantifier at the end once again prevents matching its group at that position, while enabling all of the named groups within it to be used by


职场AI,就用扣子
AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!


多风格AI绘画神器
堆友平台由阿里巴巴设计团队创建,作为一款AI驱动的设计工具,专为设计师提供一站式增长服务。功能覆盖海量3D素材、AI绘画、实时渲染以及专业抠图,显著提升设计品质和效率。平台不仅提供工具,还是一个促进创意交流和个人发展的空间,界面友好,适合所有级别的设计师和创意工作者。


零代码AI应用开发平台
零代码AI应用开发平台,用户只需一句话简单描述需求,AI能自动生成小程序、APP或H5网页应用,无需编写代码。


免费创建高清无水印Sora视频
Vora是一个免费创建高清无水印Sora视频的AI工具


最适合小白的AI自动化工作流平台
无需编码,轻松生成可复用、可变现的AI自动化工作流

大模型驱动的Excel数据处理工具
基于大模型交互的表格处理系统,允许用户通过对话方式完成数据整理和可视化分析。系统采用机器学习算法解析用户指令,自动执行排序、公式计算和数据透视等操作,支持多种文件格式导入导出。数据处理响应速度保持在0.8秒以内,支持超过100万行数据的即时分析。


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI论文写作指导平台
AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适 应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站 式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号