Non-Capturing Groups in Regular Expressions
Non-Capturing Groups in Regular Expressions are used to group parts of a pattern together without capturing the matched text for later use. They are denoted by (?: ... )
. This feature is particularly useful when you need to apply quantifiers or logical operators to a group but do not want to store the matched content in memory.
1. Basic Non-Capturing Group
A basic non-capturing group is created by wrapping the pattern in (?: ... )
. This group behaves like a regular group in terms of matching, but it does not capture the matched text.
Example:
Pattern: (?:abc)+
Matches: "abcabcabc"
Explanation: The pattern matches one or more occurrences of "abc" but does not capture the individual "abc" instances.
2. Non-Capturing Group with Quantifiers
Non-capturing groups can be combined with quantifiers to apply the quantifier to the entire group without capturing the matched text.
Example:
Pattern: (?:a|b){2}
Matches: "aa", "ab", "ba", "bb"
Explanation: The pattern matches exactly two occurrences of either "a" or "b" but does not capture the individual matches.
3. Non-Capturing Group with Logical OR
Non-capturing groups can be used with the logical OR operator |
to match one of several alternatives without capturing the matched text.
Example:
Pattern: (?:cat|dog) food
Matches: "cat food", "dog food"
Explanation: The pattern matches either "cat food" or "dog food" but does not capture the "cat" or "dog" separately.
4. Non-Capturing Group with Lookahead
Non-capturing groups can be used in conjunction with lookahead assertions to apply conditions to a group without capturing the matched text.
Example:
Pattern: (?:abc)(?=def)
Matches: "abcdef"
Explanation: The pattern matches "abc" only if it is followed by "def" but does not capture the "abc" or "def".
5. Non-Capturing Group with Lookbehind
Non-capturing groups can also be used with lookbehind assertions to apply conditions to a group without capturing the matched text.
Example:
Pattern: (?<=abc)(?:def)
Matches: "abcdef"
Explanation: The pattern matches "def" only if it is preceded by "abc" but does not capture the "abc" or "def".