Back reference of a named group

The syntax for the back reference of a named group is as follows:

    \k<group1> 

Here, group1 is the name of the named capturing group.

For example, we can write our regular expression of repeating numbers, using a named group and named back reference, as follows:

    ^(?<matchedDigits>\d+)\s+\k<matchedDigits>$ 

Here, we are defining a captured group called num to capture a number using the first, and then, we are using a back reference of the named group using \k<num>.

This will match inputs such as 1234 1234 or 989 989.

Since the named capturing groups are numbered automatically as well, we can write the same regular expression as follows:

    ^(?<num>\d+)\s+\1$ 

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.