2017-10-19 113 views
1

在java中1.8.0 我试图取代%,但它不匹配java查找和替换%

String str = "%28Sample text%29"; 

    str.replaceAll("%29", "\\)"); 

    str.replaceAll("%28", "\\("); 
    System.out.println("Replaced string is " + str); 

我已经尝试了所有这Replace symbol "%" with word "Percent"没有为我工作。提前致谢。

+0

使用'replace'你实际上并不需要匹配一个正则表达式。 –

+1

'replaceAll'不会对原始'String'对象进行任何更改。相反,结果将作为新的String对象返回。 – Alex

回答

4

它的工作。 您需要重新分配给str

str = str.replaceAll("%29", "\\)"); 

    str = str.replaceAll("%28", "\\("); 
0

Jerry06's answer是正确的。

但是你可以简单地使用URLDecoder来解码这些unicode值。

String s = "%28Hello World!%29"; 
s = URLDecoder.decode(s, "UTF-8"); 
System.out.println(s); 

将输出:(您好!世界)

0

的问题是,你误会的replaceall使用。这是基于正则表达式的替换。你需要使用什么是正常replace方法类似:如果

String str = "%28Sample text%29"; 

str=str.replace("%29", "\\)"). replace("%28", "\\("); 
System.out.println("Replaced string is " + str);