views:

74

answers:

3
x = "abcdefg"
x = x.match(/ab(?:cd)ef/)

shouldn't x be abef? it is not, it is actually abcdef

Why is it that my ?: not having any effect? (of course my understanding could very well be wrong)

+1  A: 

(?:...) still matches, it just doesn't create a new group for purposes of \1/$1/.groups(1)/etc.

Ignacio Vazquez-Abrams
So to achieve what I want, I'd have to do a = x.match(/(ab)(?:cd)(ef)/); x = a[1] + a[2]; correct?
Murali
@wizard: You could do that, yes, but the none-capturing group isn't necessary for that particular expression. `/(ab)cd(ef)/` would do the same job. `x.replace(/(ab)cd(ef)/, "$1$2");` would do it even better, but I imagine your real expression is a little more complicated than your example here :-).
Andy E
+2  A: 

Your understanding is wrong. The group will still be part of the main capture, but it won't count as a sub-expression capture. The following would return an array of two matches:

x = "abcdefg"
x = x.match(/ab(cd)ef/)

Array index 0 would be "abcdef" (the complete match) and array index 1 would be "cd", the sub-expression capture. Adding the ?: tells the regex not to care about capturing the sub-expression, the full match is still fully captured.

From your other comments, there are a number of ways you could do what you're trying to do. For instance:

x.replace(/(ab)cd(ef)/, "$1$2");
x.slice(0, x.indexOf("cd")) + x.slice(x.indexOf("cd") + 2);
Andy E
A: 

In addition to the other replies, if you really need to match only the outside expressions in regex, you would have to do something like this:

x = "abcdefg"
xarr = x.match(/(ab)(?:cd)(ef)/)
x = xarr[1] + xarr[2]

But really regex isn't meant for this case.

tloflin
Murali
Ah, yes, my bad. Too much VB.Net.
tloflin