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 a
s 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编程神器IDE
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。
全能AI智能助手,随时解答生活与工作的多样问题
问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。
实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。
一键生成PPT和Word,让学习生活更轻松
讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。
深度推理能力全新升级,全面对标OpenAI o1
科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。
一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型
Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。
AI助力,做PPT更简单!
咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。
选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。
专业的AI公文写作平台,公文写作神器
AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。
OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。
openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。
最新AI工具、AI资讯
独家AI资源、AI项目落地
微信扫一扫关注公众号