Chinmaya Hegde
Chinmaya Hegde

Reputation: 775

java find and replace %

In java 1.8.0 I am trying to replace %, but it is not matching

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

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

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

I have tried all this Replace symbol "%" with word "Percent" Nothing worked for me. Thanks in Advance.

Upvotes: 1

Views: 2164

Answers (3)

gyurix
gyurix

Reputation: 1086

The problem is that you misunderstood the usage of replaceall. It's for regex based replacements. What you need to use is the normal replace method like that:

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

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

Upvotes: 0

AxelH
AxelH

Reputation: 14572

Jerry06's answer is correct.

But you could do this simply by using URLDecoder to decode those unicode value.

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

Will output :

(Hello World!)

Upvotes: 1

Viet
Viet

Reputation: 3409

It's working. You need re-assign to str

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

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

Upvotes: 5

Related Questions