正则表达式

正则表达式(简称 regex)允许开发者将字符串与模式进行匹配,提取子匹配信息,或者只是测试字符串是否符合该模式。正则表达式在许多编程语言中都有使用,而 JavaScript 的语法则受到 Perl 的启发。

¥A regular expression (regex for short) allow developers to match strings against a pattern, extract submatch information, or simply test if the string conforms to that pattern. Regular expressions are used in many programming languages, and JavaScript's syntax is inspired by Perl.

我们鼓励你阅读 正则表达式指南 以概述可用的正则表达式语法及其工作原理。

¥You are encouraged to read the regular expressions guide to get an overview of the available regex syntaxes and how they work.

描述

¥Description

正则表达式 是形式语言理论中的一个重要概念。它们是描述可能无限的字符串集(称为语言)的一种方式。正则表达式的核心需要以下功能:

¥Regular expressions are a important concept in formal language theory. They are a way to describe a possibly infinite set of character strings (called a language). A regular expression, at its core, needs the following features:

  • 可以在该语言中使用的一组字符,称为字母表。
  • 级联:ab 表示“字符 a 后跟字符 b”。
  • 联盟:a|b 表示“ab”。
  • 克莱恩星:a* 表示“零个或多个 a 个字符”。

假设字母表是有限的(比如英文字母表的 26 个字母,或者整个 Unicode 字符集),所有的正则语言都可以通过上述特性生成。当然,很多模式用这种方式表达起来非常繁琐(比如 "10 位数字" 或 "不是空格的字符"),因此 JavaScript 正则表达式包含了很多简写,下面介绍。

¥Assuming a finite alphabet (such as the 26 letters of the English alphabet, or the entire Unicode character set), all regular languages can be generated by the features above. Of course, many patterns are very tedious to express this way (such as "10 digits" or "a character that's not a space"), so JavaScript regular expressions include many shorthands, introduced below.

注意:JavaScript 正则表达式实际上不是正则,因为 backreferences 的存在(正则表达式必须具有有限状态)。然而,它们仍然是一个非常有用的功能。

¥Note: JavaScript regular expressions are in fact not regular, due to the existence of backreferences (regular expressions must have finite states). However, they are still a very useful feature.

创建正则表达式

¥Creating regular expressions

正则表达式通常通过将模式括在正斜杠 (/) 中来创建为文字:

¥A regular expression is typically created as a literal by enclosing a pattern in forward slashes (/):

js
const regex1 = /ab+c/g;

还可以使用 RegExp() 构造函数创建正则表达式:

¥Regular expressions can also be created with the RegExp() constructor:

js
const regex2 = new RegExp("ab+c", "g");

它们没有运行时差异,尽管它们可能会对性能、静态可分析性以及使用转义字符创作人机工程学问题产生影响。有关详细信息,请参阅 RegExp 参考。

¥They have no runtime differences, although they may have implications on performance, static analyzability, and authoring ergonomic issues with escaping characters. For more information, see the RegExp reference.

正则表达式标志

¥Regex flags

标志是特殊参数,可以更改正则表达式的解释方式或其与输入文本交互的方式。每个标志对应于 RegExp 对象上的一个访问器属性。

¥Flags are special parameters that can change the way a regular expression is interpreted or the way it interacts with the input text. Each flag corresponds to one accessor property on the RegExp object.

标志 描述 对应属性
d 生成子字符串匹配的索引。 hasIndices
g 全球搜索。 global
i 不区分大小写的搜索。 ignoreCase
m 允许 ^$ 匹配换行符旁边。 multiline
s 允许 . 匹配换行符。 dotAll
u "统一码";将模式视为 Unicode 代码点序列。 unicode
v 升级到 u 模式,具有更多 Unicode 功能。 unicodeSets
y 执行从目标字符串中的当前位置开始匹配的 "sticky" 搜索。 sticky

以下部分列出了所有可用的正则表达式语法,按其语法性质分组。

¥The sections below list all available regex syntaxes, grouped by their syntactic nature.

断言

¥Assertions

断言是测试字符串在指定位置是否满足特定条件的构造,但不消耗字符。断言不能是 quantified

¥Assertions are constructs that test whether the string meets a certain condition at the specified position, but not consume characters. Assertions cannot be quantified.

输入边界断言:^$

如果设置了 m 标志,则断言当前位置是输入的开始或结束,或者是行的开始或结束。

前瞻断言:(?=...)(?!...)

断言当前位置是否遵循某种模式。

后向断言:(?<=...)(?<!...)

断言当前位置之前或不之前有某种模式。

字边界断言:\b\B

断言当前位置是字边界。

原子

¥Atoms

原子是正则表达式的最基本单位。每个原子消耗字符串中的一个或多个字符,并且匹配失败或允许模式继续与下一个原子匹配。

¥Atoms are the most basic units of a regular expression. Each atom consumes one or more characters in the string, and either fails the match or allows the pattern to continue matching with the next atom.

反向引用:\1\2

匹配先前使用捕获组捕获的匹配子模式。

捕获组:(...)

匹配子模式并记住有关匹配的信息。

字符类:[...][^...]

: 匹配字符集中或不在字符集中的任何字符。当 v 标志启用时,它还可以用于匹配有限长度的字符串。

字符类转义:\d, \D, \w, \W, \s, \S

匹配预定义字符集中或不包含的任何字符。

字符转义:\n\u{...}

匹配可能无法方便地以其字面形式表示的字符。

文字字符:ab

: 匹配特定字符。

命名反向引用:\k<name>

匹配使用命名捕获组捕获的先前匹配的子模式。

命名捕获组:(?<name>...)

匹配子模式并记住有关匹配的信息。稍后可以通过自定义名称而不是通过其在模式中的索引来标识该组。

非捕获组:(?:...)

匹配子模式而不记住有关匹配的信息。

Unicode 字符类转义:\p{...}\P{...}

匹配由 Unicode 属性指定的一组字符。当 v 标志启用时,它还可以用于匹配有限长度的字符串。

通配符:.

匹配除行终止符之外的任何字符,除非设置了 s 标志。

其他特性

¥Other features

这些特性本身不指定任何模式,但用于组合模式。

¥These features do not specify any pattern themselves, but are used to compose patterns.

析取:|

匹配由 | 字符分隔的一组替代项中的任何一个。

量词:*, +, ?, {n}, {n,}, {n,m}

匹配原子一定次数。

转义序列

¥Escape sequences

正则表达式中的转义序列是指由 \ 后跟一个或多个字符形成的任何一种语法。它们可能有不同的用途,具体取决于 \ 的后续内容。以下是所有有效 "转义序列" 的列表:

¥Escape sequences in regexes refer to any kind of syntax formed by \ followed by one or more characters. They may serve very different purposes depending on what follow \. Below is a list of all valid "escape sequences":

转义序列 其次是 意义
\B 没有任何 非字边界断言
\D 没有任何 字符类转义 代表非数字字符
\P {,Unicode 属性和/或值,然后是 } Unicode 字符类转义 表示没有指定 Unicode 属性的字符
\S 没有任何 字符类转义 代表非空白字符
\W 没有任何 字符类转义 代表非单词字符
\b 没有任何 字边界断言字符类 里面,代表 U+0008(退格键)
\c AZaz 的一封信 代表控制字符的 字符转义 其值等于字母的字符值模 32
\d 没有任何 字符类转义 代表数字字符(09
\f 没有任何 字符转义 代表 U+000C(换页)
\k <,标识符,然后 > A 命名反向引用
\n 没有任何 字符转义 代表 U+000A(换行)
\p {,Unicode 属性和/或值,然后是 } Unicode 字符类转义 表示具有指定 Unicode 属性的字符
\q {,一个字符串,然后是一个 } v-模式字符类 内有效;表示要字面匹配的字符串
\r 没有任何 字符转义 代表 U+000D(回车)
\s 没有任何 字符类转义 代表空白字符
\t 没有任何 字符转义 代表 U+0009(字符表)
\u 4 个十六进制数字;或 {,1 到 6 个十六进制数字,然后 } 字符转义 代表具有给定代码点的字符
\v 没有任何 字符转义 代表 U+000B(行制表)
\w 没有任何 字符类转义 代表单词字符(AZaz09_
\x 2 个十六进制数字 字符转义 代表给定值的字符
\0 没有任何 字符转义 代表 U+0000 (NULL)

\ 后跟任何其他数字字符将成为 遗留八进制转义序列,这在 Unicode 识别模式 中是被禁止的。

¥\ followed by any other digit character becomes a legacy octal escape sequence, which is forbidden in Unicode-aware mode.

此外,\ 后面可以跟一些非字母或数字字符,在这种情况下,转义序列始终是代表转义字符本身的 字符转义

¥In addition, \ can be followed by some non-letter-or-digit characters, in which case the escape sequence is always a character escape representing the escaped character itself:

  • \$, \(, \), \*, \+, \., \/, \?, \[, \\, \], \^, {, \|, }:到处有效
  • \-:仅在 字符类 内有效
  • \!, \#, \%, \&, \,, \:, \;, \<, \=, \>, \@, \``, ~:仅在 [v`-模式字符类](/en-US/docs/Web/JavaScript/Reference/Regular_expressions/Character_class#v-mode_character_class) 内有效

其他 ASCII 字符,即空格字符、"'_ 以及上面未提及的任何字母字符,都不是有效的转义序列。在 Unicode 不识别模式 中,不属于上述之一的转义序列将成为身份转义:它们代表反斜杠后面的字符。例如,\a 代表字符 a。此行为限制了引入新转义序列而不导致向后兼容性问题的能力,因此在 Unicode 感知模式中被禁止。

¥The other ASCII characters, namely space character, ", ', _, and any letter character not mentioned above, are not valid escape sequences. In Unicode-unaware mode, escape sequences that are not one of the above become identity escapes: they represent the character that follows the backslash. For example, \a represents the character a. This behavior limits the ability to introduce new escape sequences without causing backward compatibility issues, and is therefore forbidden in Unicode-aware mode.

规范

Specification
ECMAScript Language Specification
# prod-DecimalEscape
ECMAScript Language Specification
# prod-Atom
ECMAScript Language Specification
# prod-CharacterClass
ECMAScript Language Specification
# prod-CharacterClassEscape
ECMAScript Language Specification
# prod-CharacterEscape
ECMAScript Language Specification
# prod-Disjunction
ECMAScript Language Specification
# prod-Assertion
ECMAScript Language Specification
# prod-PatternCharacter
ECMAScript Language Specification
# prod-AtomEscape
ECMAScript Language Specification
# prod-Quantifier

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also