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

Hackerman :

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?

syeedOde :
// specify start and end of line

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=353114&siteId=1