String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
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
java.util.regex.Pattern.quote(java.lang.String)
will prevent you from making mistakes when converting a string literal to a regex. –
Achromatism 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);
}
}
String.valueOf("i++")
for? Just using i++;
should be sufficient. Also you are missing the semicolon. –
Achromatism "i++;".toString()
. –
Shakhty 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\\+\\+;", "");
© 2022 - 2024 — McMap. All rights reserved.