views:

161

answers:

2

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.

for instance:

string = "@abc @bcd @cde";

re2='@([a-z]+)';

p=new RegExp(re2,["g"]);

m=string.match(p)

for (var i in m) { alert(m[i]; }

this is returning "@abc" , "@bcd", "@cde" but I want it to return "abc", "bcd", "cde"

how do I get the latter?

+2  A: 
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]);
}
kangax
Great, this was actually surprisingly hard to find, so thanks
gatapia
A: 

You should use non-capturing group:

(?:@)([a-z]+)
Superfilin