regex

regex

JavaScript 正则表达式增强库

regex 是一个扩展 JavaScript 原生正则表达式功能的库,提供更强大和易读的语法。支持自由空格和注释、原子组、子程序和上下文感知插值等特性,保持原生性能。轻量级无依赖,支持 ES2025 正则表达式功能,内置 TypeScript 声明。可作为 Babel 插件使用,提升 JavaScript 正则表达式能力,使其与 PCRE 和 Perl 等主流实现相当。

regexJavaScript正则表达式原子组子程序Github开源项目
<div align="center"> <a href="https://github.com/slevithan/regex#readme"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://github.com/slevithan/regex/raw/main/regex-logo-dark.svg"> <img alt="regex logo" height="180" src="https://github.com/slevithan/regex/raw/main/regex-logo.svg"> </picture> </a> <br><br>

build status npm bundle size

</div>

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.

<details> <summary><b>Table of contents</b></summary> </details>

💎 Features

  • A modern regex baseline so you don't need to continually opt-in to best practices.
    • Always-on flag <kbd>v</kbd> gives you the best level of Unicode support and strict errors.
    • New flags:
      • Always-on flag <kbd>x</kbd> allows you to freely add whitespace and comments to your regexes.
      • Always-on flag <kbd>n</kbd> (named capture only mode) improves regex readability and efficiency.
    • No unreadable escaped backslashes \\\\ since it's a raw string template tag.
  • Extended regex syntax.
    • Atomic groups via (?>…) can dramatically improve performance and prevent ReDoS.
    • Subroutines via \g<name> enable powerful composition, improving readability and maintainability.
    • Subroutine definition groups via (?(DEFINE)…) allow groups within them to be used by reference only.
    • Recursive matching is enabled by a plugin.
  • Context-aware and safe interpolation of regexes, strings, and partial patterns.
    • Interpolated strings have their special characters escaped.
    • Interpolated regexes locally preserve the meaning of their own flags (or their absense), and their numbered backreferences are adjusted to work within the overall pattern.

🪧 Examples

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

🕹️ Install and use

npm install regex
import {regex, pattern} from 'regex';

In browsers:

<script type="module"> import {regex, pattern} from 'https://cdn.jsdelivr.net/npm/regex@4.0.0/+esm'; // … </script>
<details> <summary>Using a global name (no import)</summary>
<script src="https://cdn.jsdelivr.net/npm/regex@4.0.0/dist/regex.min.js"></script> <script> const {regex, pattern} = Regex; </script>
</details>

❓ Context

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>
  1. Unicode-unaware (legacy) mode is the default and can easily and silently create Unicode-related bugs.
  2. Named capture mode changes the meaning of \k when a named capture appears anywhere in a regex.
  3. Unicode mode with flag <kbd>u</kbd> adds strict errors (for unreserved letter escapes, octal escapes, escaped literal digits, and unescaped special characters in some contexts), switches to code-point-based matching (changing the potential handling of the dot, negated sets like \W, character class ranges, and quantifiers), changes flag <kbd>i</kbd> to apply Unicode case-folding, and adds support for new syntax.
  4. UnicodeSets mode with flag <kbd>v</kbd> (an upgrade to <kbd>u</kbd>) incompatibly changes escaping rules within character classes, fixes case-insensitive matching for \p and \P within negated [^…], and adds support for new features/syntax.
</details>

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.

🦾 Extended regex syntax

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

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!

<details> <summary>👉 <b>Learn more with examples</b></summary>

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:

  • The regex engine starts by using the greedy a+ within the atomic group to match all the as in the target string.
  • Then, when it tries to match the additional a outside the group, it fails (the next character in the target string is a b), so the regex engine backtracks.
  • But because it can't backtrack into the atomic group to make the + 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.

</details>

[!NOTE] Atomic groups are based on the JavaScript proposal for them as well as support in many other regex flavors.

Subroutines

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.

  1. They can reference groups that themselves contain subroutines, chained to any depth.
  2. Any capturing groups that are set during the subroutine call revert to their previous values afterwards.
  3. They don't create named captures that are visible outside of the subroutine, so using subroutines doesn't lead to "duplicate capture group name" errors.

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!!!!'.

<details> <summary>👉 <b>Show more details</b></summary>
  • Subroutines can appear before the groups they reference.
  • If there are duplicate capture names, subroutines refer to the first instance of the given group (matching the behavior of PCRE and Perl).
  • Although subroutines can be chained to any depth, a descriptive error is thrown if they're used recursively. Support for recursion can be added via a plugin (see Recursion).
  • Like backreferences, subroutines can't be used within character classes.
  • As with all extended syntax in regex, subroutines are applied after interpolation, giving them maximal flexibility.
</details> <details> <summary>👉 <b>Show how to define subpatterns for use by reference only</b></summary>

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,就用扣子

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

堆友

堆友

多风格AI绘画神器

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

图像生成AI工具AI反应堆AI工具箱AI绘画GOAI艺术字堆友相机AI图像热门
码上飞

码上飞

零代码AI应用开发平台

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

Vora

Vora

免费创建高清无水印Sora视频

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

Refly.AI

Refly.AI

最适合小白的AI自动化工作流平台

无需编码,轻松生成可复用、可变现的AI自动化工作流

酷表ChatExcel

酷表ChatExcel

大模型驱动的Excel数据处理工具

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

AI工具酷表ChatExcelAI智能客服AI营销产品使用教程
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

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

AI工具TraeAI IDE协作生产力转型热门
AIWritePaper论文写作

AIWritePaper论文写作

AI论文写作指导平台

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

AI辅助写作AI工具AI论文工具论文写作智能生成大纲数据安全AI助手热门
博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

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

AI办公办公工具AI工具博思AIPPTAI生成PPT智能排版海量精品模板AI创作热门
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

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

下拉加载更多