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 ...

Get Java 9 Regular Expressions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.