String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
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.
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.
\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With