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

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

Susan Sarandon
Release: 2024-10-31 16:03:46
Original
684 people have browsed it

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"));
Copy after login

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template