正则表达式 && ||难题

regular expression && || conundrum

如果有人能解释这是为什么,我将不胜感激。所附图片显示了 Javascript 正则表达式的控制台截图,这是我结合学习课程后尝试的。我期望在使用 OR || 时得到所有真正的布尔值运算符,至少。

带||的正则表达式运算符:

带 && 运算符的正则表达式:

您似乎假设 &&|| 适用于 "combine" 正则表达式,但布尔运算符根本不像 JavaScript 那样工作。 From MDN:

Logical operators

Logical operators are typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

如果 ab 是正则表达式对象,那么它们都是 "truthy." 对于任何两个真值,a || b 计算为 aa && b 的计算结果为 b.

A RegExp 的计算结果总是 true,所以根据 logical operator rules:

(/Mou/) || (/str/)  //=> /Mou/

(/Mou/) && (/str/)  //=> /str/

document.write( (/Mou/) || (/str/));

document.write('<br>');

document.write( (/Mou/) && (/str/) );

如果您要测试的是"Mou" "str" 在一个字符串中然后你可以使用这个 RegExp 它使用管道符号来实现逻辑 or 组的行为 (more info):

/(Mou|str)/

// or dynamically constructed:
var a = "Mou";
var b = "str";
var regexp = new RegExp('('+a+'|'+b+')');

如果你想测试的是 "Mou" AND "str" 那么你可以使用这个稍微复杂一点的构造,它利用了正向先行 (more info):

/(?=.*Mou)(?=.*str)/

// or dynamically constructed:
var a = "Mou";
var b = "str";
var regexp = new RegExp('(?=.*'+a+')(?=.*'+b+')');

相当容易出错:

&& 和 ||称为 "Short Circuit" 运算符,它们 return 第二个操作数基于第一个操作数的值。

http://www.openjs.com/articles/syntax/short_circuit_operators.php