Consider the following program (it can be compiled and run online e. g. at Javatpoint):
public class Simple
{
public static void main(String args[])
{
System.out.println("A:B:C:D".replaceFirst("(?<=[^:]*:[^:]*:).", "X"));
System.out.println("A:B:C:D".replaceFirst("(?<=(?:[^:]*:){2}).", "X"));
}
}
The second invocation of replaceFirst
throws
java.util.regex.PatternSyntaxException: Look-behind group does not have an obvious maximum length near index 16
(?<=(?:[^:]*:){2}).
^
- that's understandable. But the first invocation silently returns the string unchanged. Shouldn't the subexpressions [^:]*:[^:]*:
and (?:[^:]*:){2}
be equivalent? So what's the reason for the differing behavior?