开发者

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 long开发者_开发问答est 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 []


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


The ^ matches the start of the input string, so your regex ~^ cannot possibly match anything. You'll need to escape it in order to match the literal "^":

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

Note that the ~ is no special character and needs no escaping.

Or if you want to replace ~!, ~!~^ and ~^ in one go, try:

String x  = a.replaceAll("~!~\\^|~!|~\\^", ""); 


^ in a regular expression means start of line, so I assume java is interpreting it that way, in which case the pattern will never match anything. You need to escape it with a backslash, doubled to get it past java, so "~\\^".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜