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开发者_JS百科
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.
\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.
*
matches zero or more. Maybe I'm wrong, but wouldn't this match zero digits starting at "lorem", hence the empty string?
精彩评论