开发者

Replace \F\ in a Java String

开发者 https://www.devze.com 2023-02-07 02:32 出处:网络
I am struggling with string replacement that contains special regex characters. I got a list of separators from a file, and I need to replace the escaped form of these characters into the unescaped ch

I am struggling with string replacement that contains special regex characters. I got a list of separators from a file, and I need to replace the escaped form of these characters into the unescaped characters.

The mapping table is the following. Note that the escape character is known after parsing the file so I can’t hard code the replacement strings.

escapeChar + F + escapeChar <=> sep1
escapeChar + S + escapeChar <=> sep2
escapeChar + T + escapeChar <=> sep3
escapeChar + R + escapeChar <=> sep4
escapeChar + E + escapeChar <=> escapeChar

Let’s say that after parsing the file you have to the following separators

sep1 = | 
sep2 = ^
sep3 = &
sep4 = $
sep5 = \

So when you parse the file and the input is the following \F\\S\\T\\R\\E\. It should be translated into |^&$\

The following code is not working (I just tried with the first separ开发者_高级运维ator):

String sep1 = "|";
String escapeChar = "\\";
String x = "\\F\\\\S\\\\T\\\\R\\\\E\\";
x.replaceAll(Pattern.quote(escapeChar) + "F"
        + Pattern.quote(escapeChar), sep1);
System.out.println(x);


Strings are immutable in Java. String.replaceAll returns a new string with the replacements performed, rather than changing the contents of the existing string. Try:

x = x.replaceAll(...);

That seems to work fine, assuming I understood what you were trying to do.

0

精彩评论

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