这是代码:
reg = /(\d{3}\.){3}\d{3}/;
var str8 = "111.222.333.444";
console.log(str8.match(reg));
结果:数组 [ "111.222.333.444", "333."] 在火狐浏览器中测试
我可以期待第一个结果,但我无法期待的是第二个结果。 谁能告诉我为什么它会得到第二个结果并告诉我如何修复才能只得到 第一个。
谢谢~!
最佳答案
捕获组出现在String#match
中(不带 /g
修饰符)结果作为结果数组的一部分。
If the regular expression does not include the g flag, returns the same result as RegExp.exec().
和exec()
帮助说:
If the match succeeds, the
exec()
method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.
要摆脱它们,只需将捕获组替换为非捕获组即可:
reg = /(?:\d{3}\.){3}\d{3}/;
// ^^
var str8 = "111.222.333.444";
console.log(str8.match(reg));
结果:[“111.222.333.444”,索引:0,输入:“111.222.333.444”]
。
关于javascript - javascript 中的正则表达式出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33081841/