为什么这个正则表达式返回这样的数组

时间:2014-09-23 17:02:33

标签: javascript regex

我在MDN上遇到了这个关于字符串匹配方法的例子:

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上的匹配不是很清楚,似乎应该返回["第3.4.5.1节"," .4.5.1"],任何人都可以解释一下结果是这样的。

2 个答案:

答案 0 :(得分: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    

DEMO

要获得所需的输出,您需要以此*模式捕获以下(\.\d)*,并且还需要删除第一个捕获组。

DEMO

> var str = "For more information, see Chapter 3.4.5.1";
undefined
> var re = /chapter \d+((?:\.\d)*)/i;
undefined
> str.match(re);
[ 'Chapter 3.4.5.1',
  '.4.5.1',
  index: 26,
  input: 'For more information, see Chapter 3.4.5.1' ]

答案 1 :(得分:1)

str.match()会返回[whole 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);