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?
This regex
results in
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) ora.replaceAll("(\\(\\w\\))", "\n$1");
to match any (*) (Word character)As first argument method replaceAll expects regular expression and I highly recommend you to read about them.
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.
you have to escape the special characters: