Home  >  Article  >  Java  >  Why does String.replaceAll(regex) replace twice when using \".*\"?

Why does String.replaceAll(regex) replace twice when using \".*\"?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 16:03:46603browse

Why does String.replaceAll(regex) replace twice when using

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:

  • During the first pass, .* matches the entire string and replaces it with "a."
  • During the second pass, .* matches an empty string at the end of the input (since it can match zero characters) and replaces it with another "a."

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:

  • Use .replaceFirst() to only replace the first occurrence:
"test".replaceFirst(".*", "a")
  • Use .matches() to check if the entire string matches the given regular expression:
System.out.println("test".matches(".*")); // Prints true
  • Use a more specific regular expression, such as . which requires at least one character:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn