Murali
Murali

Reputation: 1516

Regular expression, "just group, don't capture", doesn't seem to work

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)

Upvotes: 16

Views: 12935

Answers (3)

tloflin
tloflin

Reputation: 4050

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.

Upvotes: 0

Andy E
Andy E

Reputation: 344537

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);

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

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

Upvotes: 27

Related Questions