Given this code :
String replaced = "A".replaceAll(".*", "HI");
Why does replaced
contain the string HIHI
instead of HI
as I would have guessed? It seems that it has something to do with the beginning of a line since using the pattern ^.*
yields HI
, but I don't get the reason for this.
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement .
Definition and Usage. The replace() method searches a string for a specified character, and returns a new string where the specified character(s) are replaced.
The only difference between them is that it replaces the sub-string with the given string for all the occurrences present in the string. Syntax: The syntax of the replaceAll() method is as follows: public String replaceAll(String str, String replacement)
replaceAll() With a Non-Empty Replacement We've learned the meanings of regular expressions \s and \s+. Now, let's have a look at how the replaceAll() method behaves differently with these two regular expressions. The replaceAll() method finds single whitespace characters and replaces each match with an underscore.
I think this is because .*
first matches the entire string, and then matches the empty string at the end of string. Of course, ^.*
won't match the empty string at the end of "A", so you end up with only one "HI".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With