Javascript 为什么这个regexp返回这样的数组
我在MDN for string的match方法中遇到了以下示例:Javascript 为什么这个regexp返回这样的数组,javascript,regex,Javascript,Regex,我在MDN for string的match方法中遇到了以下示例: var str = "For more information, see Chapter 3.4.5.1"; var re = /(chapter \d+(\.\d)*)/i; var found = str.match(re); console.log(found); // logs ["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"] // "Chapter 3.4.5.1" is
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match(re);
console.log(found);
// logs ["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]
// "Chapter 3.4.5.1" is the first match and the first value
// remembered from (Chapter \d+(\.\d)*).
// ".1" is the last value remembered from (\.\d)
我不太清楚JS上RegExp上的匹配,它似乎应该返回[“Chapter 3.4.5.1”,“.4.5.1”],有人能解释为什么结果是这样的吗
["Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]
| | |
| | |
Matched string Characters inside Characters inside the group index 2. Basically `*` would do a greedy match. In this (\.\d)* , it eats up all the `.\d` and captures only the last `.\d` part because you fail to capture the following `*` .
the group index
1
要获得所需的输出,您需要在此(\。\d)*
模式中捕获以下*
,并且还需要删除第一个捕获组
str.match()
返回[整个regexp match,paren1match,paren2match…]的数组。
要实现[“第3.4.5.1章”、“.4.5.1节”]您的代码应该如下所示:
var str = "For more information, see Chapter 3.4.5.1";
var re = /chapter \d+([\.\d]*)/i;
var found = str.match(re);
console.log(found);
理解你所说的,但我几乎找不到(\.\d)*的匹配和捕获行为的文档,如果你有,在这里给出,我将非常感谢(\.\d)*将匹配一系列点,后跟一个数字(.9.9.5.6.2将匹配,但5.5.5和.5..5将不匹配)。([\.\d]*)这将以任何顺序匹配一系列数字和点(99.4..56.3..15.将匹配)理解您所说的,但我几乎找不到(\.\d)*的匹配和捕获行为的文档,如果您有,请在此提供,我将不胜感激。如果“第3.4.5.1章”,请参阅我测试的链接右侧的解释
var str = "For more information, see Chapter 3.4.5.1";
var re = /chapter \d+([\.\d]*)/i;
var found = str.match(re);
console.log(found);