Hackerman
Hackerman

Reputation: 1398

Why does String.replaceAll(".*", "REPLACEMENT") give unexpected behavior in 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?

Upvotes: 6

Views: 164

Answers (1)

syeedOde
syeedOde

Reputation: 66

// specify start and end of line

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

Upvotes: 5

Related Questions