为什么String.match(/ \d * /)返回一个空字符串? [英] Why does String.match( / \d*/ ) return an empty string?

查看:233
本文介绍了为什么String.match(/ \d * /)返回一个空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我理解为什么使用\d *返回一个包含空字符串的数组,而使用\d +返回[100](如预期的那样)。我明白为什么\d +有效,但不明白为什么\d *无法正常工作。是否使用*使它返回零长度匹配,以及它是如何工作的?

Can someone help me to understand why using \d* returns an array containing an empty string, whereas using \d+ returns ["100"] (as expected). I get why the \d+ works, but don't see why exactly \d* doesn't work. Does using the * cause it to return a zero-length match, and how exactly does this work?

var str = 'one to 100';
var regex = /\d*/;
console.log(str.match(regex));
// [""]


推荐答案

记住那个匹配正在寻找它能找到的匹配给定正则表达式的第一个子字符串。

Remember that match is looking for the first substring it can find that matches the given regex.

* 表示可能有零个或多个东西,所以 \d * 表示你正在寻找一个包含0或者0的字符串更多数字。

* means that there may be zero or more of something, so \d* means you're looking for a string that contains zero or more digits.

如果您的输入字符串以数字开头,那么整个数字将匹配。

If your input string started with a number, that entire number would be matched.

"5 to 100".match(/\d*/); // "5"
"5 to 100".match(/\d+/); // "5"

但由于第一个字符是非数字, match()表示字符串的开头(没有字符)与正则表达式匹配。

But since the first character is a non-digit, match() figures that the beginning of the string (with no characters) matches the regex.

因为你的字符串不是以字符串开头的任何数字,空字符串是输入的第一个与正则表达式匹配的子字符串。

Since your string doesn't begin with any digits, an empty string is the first substring of your input which matches that regex.

这篇关于为什么String.match(/ \d * /)返回一个空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆