Named Capturing Groups
Named capture groups extend on the idea of capture groups by allowing a group to be referenced by a name, in addition to by number.
Note: group names are case-sensitive. For example, "Group" and "group" refer to two different groups.
Numbering
Named capture groups are still given group numbers, just like unnamed groups.
By default, named and unnamed groups are assigned numbers starting with the left-most group, and moving right.
For example, the regex (?<groupName>1)(2)\1\2
would match 1212
, because the named group is group 1, and the unnamed group
is group 2.
.NET numbering (flag)
If the DOTNET_NUMBERING flag is set when compiling a pattern, .NET's numbering will be used (instead of Java's).
In .NET, named capture groups are assigned their group number only after all unnamed groups.
For example, the regex (?<groupName>1)(2)\1\2
would match 1221
, because the named group is numbered after the unnamed. The
named capture group is group 2, and the unnamed group is group 1.
Duplicate Names (flag)
By default, capture group names must be unique. If multiple groups with the same name exist, a PatternSyntaxException is thrown.
By setting the DUPLICATE_NAMES flag, multiple capture groups with the same name are allowed.
Allowing duplicate names can also be enabled via the embedded flag
expression (?J)
.