String replaceAll not replacing i++;
Asked Answered
M

3

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

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

But this is not replacing i++ with blank.

Mockheroic answered 6/8, 2018 at 8:40 Comment(0)
F
8

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

Fallible answered 6/8, 2018 at 8:46 Comment(3)
"this is helpfull if you have multiple occurances of character to be replaced" - The only difference between the two function is that one uses regex and the other uses string literals. Both their description starts with "Replaces each substring of this string that matches..."Achromatism
java.util.regex.Pattern.quote(java.lang.String) will prevent you from making mistakes when converting a string literal to a regex.Achromatism
thanks for the suggestion, i have updated the answer nowFallible
P
3

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);
}  
}
Pampero answered 6/8, 2018 at 9:4 Comment(2)
What would you need String.valueOf("i++") for? Just using i++; should be sufficient. Also you are missing the semicolon.Achromatism
Or you could do "i++;".toString().Shakhty
E
2

The problem is the string that you are using to replace , that is cnsidered as regex pattern to skip the meaning you will have to use escape sequence like below.

String newCode = preCode.replaceAll("i\\+\\+;", "");
Enhance answered 6/8, 2018 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.