Non-capturing groups

There are cases while building regular expressions when we don't really want to capture any text but just want to group a subpattern to apply a boundary assertion or quantifier. This is the case for using non-capturing groups. We can mark a group as a non-capturing group by adding a question mark and a colon right after the opening parenthesis.

Note that we can also place one or more mode modifiers between the question mark and the colon. The scope of the modifier used in this manner is only effective for that group.

For example, we can use a non-capturing group in our regex to match an even number of digits:

    ^(?:d{2})+$ 

Since we are not really interested in capturing any text from a matched string, it is a good choice to use a non-capturing group here.

An example of a non-capturing group with the ignore case modifier is as follows:

    (?i:red|green|blue|white) 

Due to the presence of the i modifier, this capturing group will match all the alternations by ignoring the case. Thus, it may match red, RED, White, blue, Green, BluE, greeN, WHITE, and so on.

There are major differences between the following three regular expression patterns:

    (?:abc) 
(?mi:abc)
((?:abc)?)

In the first case, we define a non-capturing group with a pattern as abc.

In the second case, we define a non-capturing group with the m (multiline) and i (ignore case) modifiers. This allows the regex to match abc, ABC, Abc, or aBC.

In the third case, we define an optional non-capturing group inside the capturing group that matches abc or an empty string in the captured group.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.131.38.210