javascript - javascript 中的正则表达式出现意外结果

标签 javascript regex

这是代码:

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/

相关文章:

javascript - Angular 位置搜索不适用于 &

PHP正则表达式用于包含字母数字和特殊字符的字符串

ruby-on-rails - Rails number_to_percentage 和次奇怪的行为

Python正则表达式使用一个正则表达式匹配匹配的元素

c++ - 在字符串正则表达式 C++ 中查找模式

javascript - ES6 导出和导入函数

javascript - 单击事件处理程序无意中冒泡,即使在调用 jQuery 的 stopPropagation() 之后也是如此

javascript - 在 Javascript 中使用 Google 文字转语音

javascript - 如何设置符号在折线上移动的速度

regex - Scala 正则表达式从 url 中提取域