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>$";
or using numbered back references:
final String regex = "^(\d+)\s+\1$";