javascript regexp(|)管道运算符与(||)逻辑运算符的作用相同吗?

me_*_*jay 4 javascript regex logical-operators

我知道如果正则表达式两边的一个子字符串匹配,javascript中的regexp OR(|)运算符会匹配.

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

所以我想知道regexp(|)(也称为管道)OR运算符是否以相同的方式工作,或者它首先匹配两个子字符串然后决定匹配.如果我没有错,我认为只有当左手子串不匹配时才应该检查第二个右手子串.

Mik*_*uel 7

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

例如,

"The | is short circuiting, NOT!".match(/The \| is short circuiting(?:|, NOT!)/)
Run Code Online (Sandbox Code Playgroud)

产生

["The | is short circuiting"]
Run Code Online (Sandbox Code Playgroud)

"The | is not short circuiting, NOT!".match(/The \| is not short circuiting(?:, NOT!|)/)
Run Code Online (Sandbox Code Playgroud)

产生

["The | is not short circuiting, NOT!"]
Run Code Online (Sandbox Code Playgroud)

语言规范

生产Disjunction :: Alternative | Disjunction评估如下:

  1. 评估替代方案以获得匹配器m1.
  2. 评估Disjunction以获得Matcher m2.
  3. 返回一个内部Matcher闭包,它接受两个参数,一个State x和一个Continuation c,并执行以下操作:
    一个.调用m1(x,c)并将r作为结果.
    如果r没有失败,则返回r.
    C.调用m2(x,c)并返回其结果.

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