"ange134".match(/\d+/) // result => 134
"ange134".match(/\d*/) // result => "" //expected 134
Run Code Online (Sandbox Code Playgroud)
在上述情况下,+表现得很好,因为贪婪.
但为什么/\d*/不回归同样的事情呢?
"ange134".match(/\d+/) // result => 123
Run Code Online (Sandbox Code Playgroud)
在上述情况下\d+,确保必须至少有一个数字可以跟随更多,因此当扫描开始并且在开始时发现"a"时,它仍然在不满足条件时继续搜索数字.
"ange134".match(/\d*/) // result => "" //expected 123
Run Code Online (Sandbox Code Playgroud)
但是在上述情况下,\d*意味着数字出现零次或多次.因此,当扫描开始并且当它找到"a"时,条件得到满足(数字为零)...因此,您将获得空结果集.
您可以放置全局标志/g以使其继续搜索所有结果.请参阅此链接以了解行为如何随全局标志更改.尝试打开和关闭它以更好地理解它.
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 getsRun Code Online (Sandbox Code Playgroud)