Bug in JDK Javadoc for class java.util.regex.Pattern

The Javadoc for class java.util.regex.Pattern contains a bug. It says that a back reference (Pattern (Java Platform SE 6)) to a capturing group is depicted by \n whereas n denotes the number of the capturing group. Unfortunately this won’t work. Use $n instead.

Wrong:

public class BackRefWrong {
	public static void main(String args[]) {
		 System.out.println( "123".replaceAll("^.*(2).*$", "\1"));
		}
}

Output:

Correct:

public class BackRefCorrect {
	public static void main(String args[]) {
		 System.out.println( "123".replaceAll("^.*(2).*$", "$1"));
		}
}

Ouput: 2

Leave a Reply

Your email address will not be published. Required fields are marked *