5

I have the following code:

var str = "$123";
var re = /(\$[0-9]+(\.[0-9]{2})?)/;
var found = str.match(re);

alert(found[1]);
alert(found[0]);

I am trying to understand why found[0] and found[1] would contain $123. Why does it get it twice?

I would like to get all the "potential" prices just one, so for example if I have this string:

var str = "$123 $149 $150"; It would be:

found[0] = $123
found[1] = $149
found[2] = $150

And that would be it, the array found would not have more matches.

What is happening here? What am I missing?

4

3 回答 3

7

这是因为围绕整个表达式的括号:它定义了一个捕获的组。

当您不使用该g标志时,match以数组形式返回:

  • 如果它与模式匹配,则为整个字符串
  • 捕获的组

这里捕获的组是整个字符串。

你似乎想要的是

"$123 $149 $150".match(/\$\d+(\.\d{0,2})?/g)

返回

["$123", "$149", "$150"]

参考:关于正则表达式和标志的 MDN

于 2013-10-29T17:17:05.123 回答
6

首先是全场比赛。

第二个代表您定义的外部子组,与您的情况下的完全匹配相同。

该特定子组似乎并不需要,因此您应该能够将其删除。内部组与您的特定字符串不匹配。


仅供参考,如果你想使用一个组,但让它不被捕获,你可以?:在它的开头添加。

var re = /(?:\$[0-9]+(\.[0-9]{2})?)/;

同样,这里的组对你没有多大好处,但它显示了?:正在使用中。

于 2013-10-29T17:16:36.870 回答
2

g标志添加到正则表达式的末尾。否则只会捕获第一个匹配项。使用g,不捕获子组。你不需要它们;正则表达式中的外括号实际上并没有做任何事情。

var re = /\$[0-9]+(\.[0-9]{2})?/g;

您可以使用 显式抑制子组捕获(?:,但与g标志无关。

于 2013-10-29T17:19:23.620 回答