为什么正则表达式使用Java中的“匹配"两次获得价值? [英] Why regex gets value twice using 'match' in Javascript?

查看:48
本文介绍了为什么正则表达式使用Java中的“匹配"两次获得价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

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

我试图理解为什么found [0]和found [1]包含$ 123.为什么会两次?

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"; 它将是:

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?

推荐答案

这是因为整个表达式带有括号:它定义了一个捕获的组.

That's because of the parenthesis around the whole expression : it defines a captured group.

当您不使用 g 标志时, match 返回一个数组:

When you don't use the g flag, match returns in an array :

  • 整个字符串(如果与模式匹配)
  • 捕获的组

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

Here the captured group is the whole string.

您似乎想要的是

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

返回

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

参考资料:有关正则表达式和标志的MDN

这篇关于为什么正则表达式使用Java中的“匹配"两次获得价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆