Why String.replaceAll(regex) Replaces Twice
In the code snippet:
System.out.println("test".replaceAll(".*", "a"));
the regular expression .* matches any character, including zero characters. This means that it can match the entire string twice:
This behavior is not considered a bug in the Java regex engine. Instead, it is a consequence of the way .* matches any character.
Alternatives
To avoid this behavior, you can use the following alternatives:
"test".replaceFirst(".*", "a")
System.out.println("test".matches(".*")); // Prints true
System.out.println("test".replaceAll(".+", "a")); // Prints a
The above is the detailed content of Why does String.replaceAll(regex) replace twice when using \'.*\'?. For more information, please follow other related articles on the PHP Chinese website!