Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to replace a entire String with new value using String replaceAll method in Java

Tags:

java

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" .

like image 558
kannanrbk Avatar asked May 04 '12 12:05

kannanrbk


People also ask

How do I replace an entire string with another string in Java?

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.

Does replaceAll replace string?

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.

What is replaceAll \\ s in Java?

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.

What is the difference between Replace () and replaceAll ()?

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.


2 Answers

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.

like image 112
Nick Garvey Avatar answered Nov 03 '22 18:11

Nick Garvey


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.

like image 43
Marko Topolnik Avatar answered Nov 03 '22 16:11

Marko Topolnik