Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string with the regular expression ".*" returns the replacement twice [duplicate]

Tags:

java

regex

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.

like image 590
maerch Avatar asked Apr 22 '13 10:04

maerch


People also ask

What is the return type of string replace () method?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement .

What does the replace () method do?

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.

What is the difference between Replace () and replaceAll ()?

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)

What does replaceAll \\ s+ do?

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.


1 Answers

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".

like image 177
Étienne Miret Avatar answered Nov 12 '22 23:11

Étienne Miret