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

Replacement reference of a named group

We haven't yet discussed the Java API for regular expression replacement, but just for reference, it will be pertinent to discuss the syntax of a named group reference in a replacement string:

  • ${group1}: This will be replaced in the resulting string by the matched content of the named captured group, group1
  • $1: This will be replaced in the resulting string by the matched content of the captured group number 1

Note that the double escaping of String while defining a Java regular expression should be applied here in defining named groups, named back references, and numbered back references. Thus, repeating the previous regular expressions used in Java code:

 final String regex = "^(?<num>\\d+)\\s+\\k<num>$"; ...

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