我知道,如果正则表达式两边的子字符串之一匹配,则 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!"]
The production Disjunction :: Alternative
|
Disjunction evaluates as follows:
- Evaluate Alternative to obtain a Matcher m1.
- Evaluate Disjunction to obtain a Matcher m2.
- 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/