javascript - javascript 正则表达式 (|) 管道运算符是否与 (||) 逻辑运算符相同?

标签 javascript regex logical-operators

我知道,如果正则表达式两边的子字符串之一匹配,则 javascript 中的正则表达式或 (|) 运算符匹配。

我还知道,在 JavaScript 中,逻辑 (||) OR 运算符仅在第一个操作数为假时才检查第二个操作数。

所以我想知道正则表达式 (|)(也称为管道)OR 运算符是否以相同的方式工作,或者它首先匹配两个子字符串,然后再决定匹配。 如果我没记错的话,我认为为了性能起见,它应该仅在左侧子字符串不匹配时才检查右侧第二个子字符串。

最佳答案

是的,正则表达式中的|是短路。

例如,

"The | is short circuiting, NOT!".match(/The \| is short circuiting(?:|, NOT!)/)

产生

["The | is short circuiting"]

同时

"The | is not short circuiting, NOT!".match(/The \| is not short circuiting(?:, NOT!|)/)

产生

["The | is not short circuiting, NOT!"]

language specification

The production Disjunction :: Alternative | Disjunction evaluates as follows:

  1. Evaluate Alternative to obtain a Matcher m1.
  2. Evaluate Disjunction to obtain a Matcher m2.
  3. Return an internal Matcher closure that takes two arguments, a State x and a Continuation c, and performs the following:
    a. Call m1(x, c) and let r be its result.
    b. If r isn't failure, return r.
    c. Call m2(x, c) and return its result.

15.10.2.3第3b行是指定短路的地方。

关于javascript - javascript 正则表达式 (|) 管道运算符是否与 (||) 逻辑运算符相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13559826/

相关文章:

用字符串中的平均值替换范围

JavaScript:逻辑运算符 `A && B` 的反义词是什么?

javascript - Javascript 中原型(prototype)的构造函数

javascript - 通过 jQuery.Ajax 下载文件

javascript - 正则表达式删除URL中的字符串

regex - 如何在正则表达式中选择多个多行组

java - if条件检查在JAVA中的任何一点是否只有一个变量是四个变量的集合

c - 变量中的逻辑运算符和初始化

javascript - 如何为 JavaScript 重定向和关闭添加延迟?

javascript - Highcharts - 从顶部开始的位置柱形图