O'Reilly logo

Java 9 Regular Expressions by Anubhava Srivastava

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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$ 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required