user3328309
user3328309

Reputation: 41

Find and replace parentheses in a string

I have the following string:

"Learning (Java) to create app on (Android)"

I would like to change it to:

"Learning <strong>Java</strong> to create app on <strong>Android</strong>"

That means replacing the parentheses with strong tags to make it bold. How I can do that with Java.

Upvotes: 1

Views: 1688

Answers (2)

Sanjeev
Sanjeev

Reputation: 9946

You can do it this way as well

String test = "Learning (Java) to create app on (Android)";

System.out.println(test.replaceAll("\\((\\w*)\\)","<b>$1</b>"));

Upvotes: 4

Jonny Henly
Jonny Henly

Reputation: 4233

The other answer's suggestion of using String#replace would do the trick if you only had one set of parentheses. However, your example has more than one set of parentheses, so what you want to use is String#replaceAll.

For instance:

String foo = "Learning (Java) to create app on (Android)";
foo = foo.replaceAll("(", "<strong>");
foo = foo.replaceAll(")", "</strong>");

Upvotes: 2

Related Questions