String x = "Welcome to Java World";
System.out.println(x.replaceAll(".*","JAVA"));
Actual Output = "JAVAJAVA" .
Excepted Output = "JAVA".
Can anybody help why it replace like this . ".*" all characters in a original string and replace this with "JAVA" . Why this returns "JAVAJAVA" .
To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.
The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with the new string.
Your regular expression can match 0 to all characters. First, it matches the entire string "Welcome to Java World"
, then it matches the end of the string ""
, replacing both with "JAVA"
.
To make this work how you expect it, you have a couple options.
String x = "Welcome to Java World";
System.out.println(x.replaceAll(".+","JAVA"));
Notice the + instead of the *, this means 1 or many, so the end won't be matched.
or
String x = "Welcome to Java World";
System.out.println(x.replaceFirst(".*","JAVA"));
This will only replace the entire string with "JAVA"
, the empty end of the string won't be replaced.
You don't need replaceAll
for your mission. The exact same semantics are achieved by simply stating
System.out.println("JAVA");
Since String
is immutable in Java, you cannot avoid getting a new object.
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