2017-10-08 109 views
4
"ange134".match(/\d+/)  // result => 134 
"ange134".match(/\d*/)  // result => ""  //expected 134 

在上述情况下表现+不同,+表现好,通过贪婪。*和在正则表达式

但为什么/\d*/不会返回相同的东西?

+5

'\ d *'匹配“ange”之前的零长度字符串。贪婪不会改变第一场比赛返回的事实。 – Ryan

+0

对于第一部分,我猜,答案应该是134。 – Miraj50

+0

不是*贪心就像+ –

回答

6
"ange134".match(/\d+/)  // result => 123 

在上述情况下\d+确保具有一定是至少一个数字可以之后更因此当扫描开始,它发现“一”在开始的时候仍保持搜索数字不符合条件。

"ange134".match(/\d*/)  // result => ""  //expected 123 

然而,在上述情况下,\d*意味着数字的或多个发生。所以,当扫描开始时,当它发现“a”条件得到满足(这是数字零发生)...因此,你得到空结果集。

你可以把全球国旗/g,使它继续搜索所有结果。请参阅此link以了解行为如何随全局标志更改。尝试打开和关闭以更好地理解它。

console.log("ange134".match(/\d*/)); 
 
console.log("ange134".match(/\d*$/)); 
 
console.log("ange134".match(/\d*/g)); 
 
console.log("134ange".match(/\d*/)); // this will return 134 as that is the first match that it gets

0
"ange134".match(/\d*/); 

手段 “0次或多次匹配号字符”。正如Ryan在上面指出的那样,一个空字符串满足这个正则表达式。尝试:

"ange134".match(/\d*$/); 

,你可以看到,它实际上是工作 - 只是需要一些情况下,如果你的目标是该字符串的134部分匹配。

0
"ange134".match(/\d*/) //means 0 or more times, and this match in the first 
//letter (because it "returns false") because you aren't using global flag that search in the whole string 

,如果你想要的工作,然后使用全局标志:

"ange134".match(/\d*/g) 

,或使用你的第一个正确的选项没有一个标志:

"ange134".match(/\d+/) 

在这个环节上存在的一个解释为什么它匹配第一个“a”字母:https://regex101.com/r/3ItllY/1/