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

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

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

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多