Named groups

In Java regular expressions, capturing groups can be defined in two ways:

  1. Using numbers that get incremented automatically (as we discussed earlier).
  2. Using names.

Starting from Java 7, the regular expressions API offers support for named capturing groups. Named capturing groups are especially useful where there are lots of capturing groups. If we have to insert a new group or remove an existing group, then the numerical order changes for every capturing group that comes after the new or removed group, thus requiring the updating of all those references.

The syntax for defining a capturing group is as follows:

    (?<name>RE) 

In the preceding line, RE is the pattern we are using for capturing a group.

There are certain rules to ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.