Search code examples
javastringstr-replacereplaceall

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.


Solution

  • 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