Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does String.replaceAll(".*", "REPLACEMENT") give unexpected behavior in Java 8?

Tags:

java

regex

java-8

Java 8's String.replaceAll(regexStr, replacementStr) doesn't work when the regex given is ".*". The result is double the replacementStr. For example:

String regexStr = ".*";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);

// Expected Result: finalStr == "REPLACEMENT"
// Actual Result: finalStr == "REPLACEMENTREPLACEMENT"

I know replaceAll() doesn't exactly make sense to use when the regex is ".*", but the regex isn't hardcoded and could be other regex strings. Why doesn't this work? Is it a bug in Java 8?

like image 752
Hackerman Avatar asked Mar 23 '20 20:03

Hackerman


1 Answers

// specify start and end of line

String regexStr = "^.*$";
String replacementStr = "REPLACEMENT"
String initialStr = "hello";
String finalStr = initialStr.replaceAll(regexStr, replacementStr);
like image 129
syeedOde Avatar answered Nov 16 '22 15:11

syeedOde