无法理解 javascript String.match(regexp) 方法的行为
我有下一个 JS 代码:
var str = 'some string';
var rexp = /^([^#]+)/;
var matchArr = str.match(rexp);
matchArr 然后包含两个项目 matchArr[0] = 'some string' 和 matchArr[1] = '某个字符串';而我期望数组中只有一项。
我无法理解这种行为。当我删除括号时,matchArr 仅包含一个匹配项。为什么会出现这种情况,有谁能解释一下吗?
I have next JS-code:
var str = 'some string';
var rexp = /^([^#]+)/;
var matchArr = str.match(rexp);
matchArr then contains two items matchArr[0] = 'some string' and
matchArr[1] = 'some string'; Whereas I'm expecting the array with only one item.
I can't understand this behavior. When I remove parentheses, then matchArr contains only one match. Why this happens, does anybody can explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您在正则表达式中使用捕获括号时,它会为整体匹配和每组捕获括号添加一个项目到返回的结果数组中。
matchArr[0]
是匹配的所有内容。matchArr[1]
是在第一组捕获括号中匹配的内容matchArr[2]
是在第二组捕获括号中匹配的内容依此类推
因此,在您的正则表达式
/^([^#]+)/
中,matchArr[0]
和matchArr[1] 之间没有区别
因为所有匹配的内容都在捕获括号中。如果您这样做:
您会发现:
因为匹配的某些部分不在捕获括号中。
或者如果你这样做:
你会发现:
When you use capturing parentheses in your regular expression, it adds an item to the returned results array for the overall match and each set of capturing parentheses.
matchArr[0]
is everything that was matched.matchArr[1]
is what matches in the first set of capturing parenthesesmatchArr[2]
is what matches in the second set of capturing parenthesesand so on
So, in your regex
/^([^#]+)/
, there is no difference betweenmatchArr[0]
andmatchArr[1]
because everything that matches is in the capturing parentheses.If you did this:
You would find that:
because there are parts of the match that are not in the capturing parentheses.
Or if you did this:
You would find that: