2017-02-23 84 views
0

需要您的帮助来了解何时使用什么。与字符串"sxcvgyb"上的方法test()一起使用时,/x.*y//x(?=.*y)/都给出了相同的结果(true)。JavaScript正则表达式:`/ x。* y /`与`/ x(?=。* y)/`

+0

如果你只是检查一个布尔结果(匹配或不匹配),它们是等价的。 – melpomene

+0

https://regex101.com/r/gisqMQ/1 vs https://regex101.com/r/nEEYZ6/1;检查右侧的说明面板。 – Aaron

+1

你应该接受一个答案。 –

回答

4

/x.*y//x(?=.*y)/对于您的目的,使用test方法时是相同的。

后者使用a regular expression "look-ahead" group (?=...),因此在匹配时没有在技术上捕获.*y,但是当您只需要知道匹配是否存在时,这没有可察觉的效果。

TL; DR:选择较短的正则表达式,/x.*y/

// Identical when using `RegExp#test` 
 
console.log(/x.*y/ .test('xylophone')) //=> true 
 
console.log(/x(?=.*y)/.test('xylophone')) //=> true 
 

 
// Different when using `RegExp#exec` 
 
console.log(/x.*y/ .exec('xylophone')) //=> [ 'xy' ] 
 
console.log(/x(?=.*y)/.exec('xylophone')) //=> [ 'x' ]

1

由于使用的是具有test方法,其结果将是相同的这种情况下:

RegExp.prototype.test()

test()方法执行搜索常规 表达式和一个指定的字符串。返回true或false。

返回

如果存在匹配正则表达式之间以及 指定的字符串; 否则,错误。

编号:Developer Mozilla - RegExp.test()

例如,下面一起来看看:

const str = "sxcvgyb" 
 

 
const test1 = RegExp(/x.*y/).test(str); 
 
const result1 = str.match(/x.*y/); 
 

 
const test2 = RegExp(/x(?=.*y)/).test(str); 
 
const result2 = str.match(/x(?=.*y)/); 
 

 
console.log('1st regex, is there a match? ', test1); 
 
console.log('1st regex, what was matched? ', result1); 
 
console.log('2nd regex, is there a match? ', test2); 
 
console.log('2nd regex, what was matched? ', result2);

它们都匹配的东西,从而test结果为真。但如果你看看实际匹配的是什么,你可以看到它们的差异。

如果您想了解更多关于它们的区别,@gyre的答案可以很好地解释“预见”组。

而且作为@Aaron建议,我还建议您使用在线测试仪,如regex101,看看你的正则表达式。理解它甚至更好地密切关注解释面板。

相关问题