How to replace a substring with ( from a string

2019-09-30 02:19发布

I have a string like following

Want to Start (A) Programming and (B) Designing

I want to replace (A) with \n(A) and (B) with \n(B) So ,the expected result will be like

Want to Start
(A) Programming and 
(B) Designing

I've tried

stringcontent=stringcontent.replaceAll("(A)", "\n(A)");

It's not working. After searching in google, I realized its because of special characters ( and ) in string.

Any possible way to solve this?

3条回答
淡お忘
2楼-- · 2019-09-30 02:39

This regex

String a = "Want to Start (A) Programming and (B) Designing";
String b = a.replaceAll("\\(", "\n\\(");
System.out.println(b);

results in

Want to Start 
(A) Programming and 
(B) Designing

Just escape the brackets with \\ and you're fine.

Edit: more specific, like mentioned below

a.replaceAll("(\\([AB]\\))", "\n$1"); to match only (A) and (B) or

a.replaceAll("(\\(\\w\\))", "\n$1"); to match any (*) (Word character)

查看更多
Lonely孤独者°
3楼-- · 2019-09-30 02:40

As first argument method replaceAll expects regular expression and I highly recommend you to read about them.

stringcontent.replaceAll("\\((?=\\w\\))", "\n(");

EDIT:

Proposed answers use hardcoded letter for checking and replacement (or assume that there is no text in braces). My answer uses \w wildcard that matches with letter together with advanced checking that makes sure letter and closing brace follows your opening brace. What answer to use is up to you.

查看更多
Viruses.
4楼-- · 2019-09-30 02:43

you have to escape the special characters:

stringcontent=stringcontent.replaceAll("\\(A\\)", "\n(A)");
查看更多
登录 后发表回答