如何在javascript正则表达式匹配中将多个匹配(/ g)与反向引用相结合 [英] how do I combine multiple matches (/g) with backreferences in javascript regex match

查看:123
本文介绍了如何在javascript正则表达式匹配中将多个匹配(/ g)与反向引用相结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用/ g(获取多个匹配项)和括号(获取反向引用)时,我对正则表达式匹配返回的数组感到困惑。我不清楚如何获得反向引用,因为匹配数组的下标似乎是指多个匹配,而不是后引用。

I'm confused about the array returned by a regex match when using both /g (to get multiple matches) and parentheses (to get backreferences). It's not clear to me how to get the backreferences because the subscript of the match array seems to refer to the multiple matches, not the back references.

例如:

string = "@abc @bcd @cde";    
re2 = '@([a-z]+)';    
p = new RegExp(re2,["g"]);    
m = string.match(p)   
for (var i in m) { alert(m[i]; }

这是返回@ abc,@ bcd,@ cde

但是我希望它返回abc,bcd,cde

我如何获得后者?

推荐答案

var str = "@abc @bcd @cde",
    re = /@([a-z]+)/g,
    match;

while (match = re.exec(str)) {
  // match[1] contains text matched by first group, match[2] - second, etc.
  alert(match[1]);
}

这篇关于如何在javascript正则表达式匹配中将多个匹配(/ g)与反向引用相结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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