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>$"; ...

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.