Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 842
Murali Avatar asked Mar 29 '10 23:03

Murali


People also ask

What does capture mean in regex?

capturing in regexps means indicating that you're interested not only in matching (which is finding strings of characters that match your regular expression), but you're also interested in using specific parts of the matched string later on.

What is the use of (? S in regular expression?

The Difference Between \s and \s+ For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What is capturing group in regex JavaScript?

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. Backreferences refer to a previously captured group in the same regular expression.


2 Answers

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

like image 135
Ignacio Vazquez-Abrams Avatar answered Oct 06 '22 09:10

Ignacio Vazquez-Abrams


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);
like image 32
Andy E Avatar answered Oct 06 '22 10:10

Andy E