1

我有分组括号()(?: )即使括号内的表达式不匹配,我也需要匹配。我已经看到|?用于此(即(a|b|c|)(a|b|c)?),但应该使用/更有效,为什么?

由于不同的 JavaScript 引擎对正则表达式的解释不同,我专门使用 SpiderMonkey 引擎。然而,一个通用的(语言方面和引擎方面的)答案会很好。

编辑:一个具体的例子是DuckDuckGo Frequency goodie。为什么作者在这种情况下选择|了呢??

4

2 回答 2

1

根据您的描述,听起来合适的选择是?量词,它直接允许选择匹配括号之间的前一个组。

另一方面,|当您想要匹配一组模式中的一个时使用。

于 2012-10-14T23:07:08.597 回答
1

要检查性能,请参阅this fiddle


使用?with grouping 或|with empty string 作为选项可能会导致意外结果!

情侣测试:

var myString = "this is a test string"; 
var myRegexp = /(test)?/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // returns empty string

var myString = "this is a string"; 
var myRegexp = /(test)?/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // returns empty string

var myString = "this is a test string"; 
var myRegexp = /(test|)/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // returns empty string

var myString = "this is a string"; 
var myRegexp = /(test|)/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // returns empty string

var myString = "this is a test string"; 
var myRegexp = /(test)/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // returns "test"

这以错误结束:

var myString = "this is a string"; 
var myRegexp = /(test)/; 
var match = myRegexp.exec(myString); 
alert(match[0]); // error

这可能是您的解决方案:

var myString = "this is a test string"; 
var myRegexp = /^(?:.*(test)|(?!.*test))/; 
var match = myRegexp.exec(myString); 
alert(match[1]); // returns "test"

var myString = "this is a string"; 
var myRegexp = /^(?:.*(test)|(?!.*test))/; 
var match = myRegexp.exec(myString); 
alert(match[1]); // returns undefined

用这个 fiddle测试上面的代码。

于 2012-10-14T23:28:00.190 回答