Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replaceAll not replacing i++;

String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");

// Desired output :: newCode = "helloworld";

But this is not replacing i++ with blank.

like image 257
Android Guy Avatar asked Aug 06 '18 08:08

Android Guy


People also ask

Does replaceAll replace original 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.

How do you replace instead of replaceAll?

Java String replaceAll() Method Example 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.

What is replaceAll \\ s+?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

What is replaceAll \\ s in Java?

Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.


2 Answers

just use replace() instead of replaceAll()

String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");

or if you want replaceAll(), apply following regex

String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");

Note : in the case of replace() the first argument is a character sequence, but in the case of replaceAll the first argument is regex

like image 82
Navneet Krishna Avatar answered Sep 26 '22 02:09

Navneet Krishna


try this one

 public class Practice {
 public static void main(String...args) {
 String preCode = "Helloi++;world";
 String newCode = preCode.replace(String.valueOf("i++;"),"");
 System.out.println(newCode);
}  
}
like image 41
Machhindra Neupane Avatar answered Sep 26 '22 02:09

Machhindra Neupane