正则表达式星号
也许我错过了一些东西,但是这个正则表达式有什么问题吗?
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 ?
您能否解释一下为什么 /\d*/.exec(str);
返回空字符串而不是“12345”。 *
表示零个或多个匹配项。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
\d*
匹配一行中的零个或多个数字。当您在正则表达式上运行exec
时,它会从输入的开头开始,并返回它找到的给定模式的第一个实例。那么该字符串中
\d*
的第一个实例在哪里?嗯,它是字符串中第一个位置,其后有零个或多个数字。但它们都后面有零个或多个数字!那里要么有数字,要么没有,但无论哪种方式都匹配。因此\d*
的第一个实例只是一个从字符串中第一个位置开始的零长度子字符串。\d*
matches zero or more digits in a row. When you runexec
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.*
匹配零个或多个。也许我错了,但这不会匹配从“lorem”开始的零位数字,因此是空字符串吗?*
matches zero or more. Maybe I'm wrong, but wouldn't this match zero digits starting at "lorem", hence the empty string?