What is the difference between (?: ) and (?= ) I assume that the first returns the text that it matches in a match function (but doesn't when applied to a sub expression group number, but not sure if I am right. Thank in advance :-) I know what they are used for, but I am not sure how they act differently. Also can repetition characters be applied to look ahead assertions?
2 Answers
(?: ) creates a group that won't be captured, i.e. stored in any back references. It usually used where you need a group but don't care about having it in a capturing group. This increases performance and unclutters backreferences.
(?= ) is a lookahead assertion. It is used to look for something whilst not consuming any characters as a match.
Comments
So the thing about both of these constructs is that the don't return anything. (?: ... ) is used the same way as ordinary ( ... ) except that its result is not captured and not returned. In Perl, and I believe in Javascript, this can lead to faster performance due to the Regex engine not having to remember the matched substrings.
The idea of (?= ) is different. You can think of any component of a regex as sort of "eating up" some subset of the matched string. But not with (?= ). Another way to think of it is that whatever comes after the (?= ) matches at the exact same place in the string that the (?= ) itself matches, not after the end of it like a normal group.
2 Comments
() and non-capturing (?:) groups. With non-capturing you cannot find out afterwards what text from the source matched that particular subpattern, only that it must have matched if the whole pattern matched.