Search code examples
javastringescapingreplaceall

replacing special chars with .replaceAll


Hello I want to replace the following chars within a string

String a = "20001=EDTS~^20002=USA~^20003=1170871875~^20004=1~^20005=0~^773=~^665=~^453=2~^448=0A";    
System.out.println(a);
String x  = a.replaceAll("~^", "");
System.out.println(x);

however my output is:

20001=EDTS~^20002=USA~^20003=1170871875~^20004=1~^20005=0~^773=~^665=~^453=2~^448=0A
20001=EDTS~^20002=USA~^20003=1170871875~^20004=1~^20005=0~^773=~^665=~^453=2~^448=0A

So clearly something is up!

I have ran it with the escape chars:

 String x  = fix.replaceAll("\\~^", "\\");

Still the same output. Is there something associated with the ~ I am unaware of?

I must do the same for:

~!~^

~!

all within the same string I figure 3 .replaceAll longest first then the two others. However I cannot get even the simplest to work :S

EDITED: for some reason the got removed

Edit2: it should be replacing the ~^ with a character box that looks similar to []


Solution

  • From what I can tell you don't need a regular expression at all?

    If no regular expression is required, you can use replace instead of replaceAll which will also replace all occurences but it won't interpret the first argument as a regular expression (see String.replace)

    String a = "20001=EDTS~^20002=USA~^20003=1170871875~^20004=1~^20005=0~^773=~^665=~^453=2~^448=0A";    
    System.out.println(a);
    String x  = a.replace("~^", "");
    System.out.println(x);
    

    This will output:

    20001=EDTS~^20002=USA~^20003=1170871875~^20004=1~^20005=0~^773=~^665=~^453=2~^448=0A
    20001=EDTS20002=USA20003=117087187520004=120005=0773=665=453=2448=0A