析取:|

析取指定多个选择。与输入匹配的任何替代项都会导致整个析取被匹配。

¥A disjunction specifies multiple alternatives. Any alternative matching the input causes the entire disjunction to be matched.

语法

¥Syntax

regex
alternative1|alternative2
alternative1|alternative2|alternative3|

参数

¥Parameters

alternativeN

一种替代模式,由 原子和断言 序列组成。成功匹配一个替代项会导致整个析取被匹配。

描述

¥Description

| 正则表达式运算符分隔两个或多个替代项。该模式首先尝试匹配第一个选项;如果失败,它会尝试匹配第二个,依此类推。例如,以下内容匹配 "a" 而不是 "ab",因为第一个替代项已成功匹配:

¥The | regular expression operator separates two or more alternatives. The pattern first tries to match the first alternative; if it fails, it tries to match the second one, and so on. For example, the following matches "a" instead of "ab", because the first alternative already matches successfully:

js
/a|ab/.exec("abc"); // ['a']

| 运算符在正则表达式中具有最低优先级。如果你想使用析取作为更大模式的一部分,则必须对其进行 group

¥The | operator has the lowest precedence in a regular expression. If you want to use a disjunction as a part of a bigger pattern, you must group it.

当分组析取后面有更多表达式时,匹配首先选择第一个替代项并尝试匹配正则表达式的其余部分。如果正则表达式的其余部分无法匹配,则匹配器会尝试下一个替代方案。例如,

¥When a grouped disjunction has more expressions after it, the matching begins by selecting the first alternative and attempting to match the rest of the regular expression. If the rest of the regular expression fails to match, the matcher tries the next alternative instead. For example,

js
/(?:(a)|(ab))(?:(c)|(bc))/.exec("abc"); // ['abc', 'a', undefined, undefined, 'bc']
// Not ['abc', undefined, 'ab', 'c', undefined]

这是因为通过在第一个备选方案中选择 a,可以在第二个备选方案中选择 bc 并导致成功匹配。这个过程称为回溯,因为匹配器首先超越析取,然后在后续匹配失败时返回析取。

¥This is because by selecting a in the first alternative, it's possible to select bc in the second alternative and result in a successful match. This process is called backtracking, because the matcher first goes beyond the disjunction and then comes back to it when subsequent matching fails.

另请注意,不匹配的替代项内的任何捕获括号都会在结果数组中生成 undefined

¥Note also that any capturing parentheses inside an alternative that's not matched produce undefined in the resulting array.

替代项可以为空,在这种情况下它与空字符串匹配(换句话说,始终匹配)。

¥An alternative can be empty, in which case it matches the empty string (in other words, always matches).

无论匹配方向如何(在 lookbehind 中相反),始终尝试从左到右进行替代。

¥Alternatives are always attempted left-to-right, regardless of the direction of matching (which is reversed in a lookbehind).

示例

¥Examples

匹配文件扩展名

¥Matching file extensions

以下示例匹配文件扩展名,使用与 输入边界断言 文章相同的代码:

¥The following example matches file extensions, using the same code as the input boundary assertion article:

js
function isImage(filename) {
  return /\.(?:png|jpe?g|webp|avif|gif)$/i.test(filename);
}

isImage("image.png"); // true
isImage("image.jpg"); // true
isImage("image.pdf"); // false

规范

Specification
ECMAScript Language Specification
# prod-Disjunction

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看