Regular Expression Star Symbol

拟墨画扇 提交于 2019-12-13 17:42:02

问题


Maybe I have missed something, but what are wrong with this regular expresion?

var str = "lorem ipsum 12345 dolor";
var x = /\d+/.exec(str);
var y = /\d*/.exec(str);
console.log(x); // will print 12345
console.log(y); // will print "" but why ? 

Can you please explain why /\d*/.exec(str); returns an empty string instead of "12345". * means zero or more number of matches.


回答1:


\d* matches zero or more digits in a row. When you run exec on a regex, it starts at the beginning of the input and returns the first instance it finds of your given pattern.

So where is the first instance of \d* in that string? Well, it's the first position in the string that has zero or more numbers after it. But they all have zero or more numbers after them! Either there are numbers there, or there aren't, but either way it matches. So the first instance of \d* is simply a zero-length substring beginning at the first position in the string.




回答2:


* matches zero or more. Maybe I'm wrong, but wouldn't this match zero digits starting at "lorem", hence the empty string?



来源:https://stackoverflow.com/questions/6865159/regular-expression-star-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!