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” .
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.
Notice the + instead of the *, this means 1 or many, so the end won’t be matched.
or
This will only replace the entire string with
"JAVA", the empty end of the string won’t be replaced.