2

In the code below I'm trying to replace in text occurrences of fromString withtoString, but no replacement takes place. How to set the parenthesis in the regex to make this work?

public static void main(String[] args) {

    String fromString = "aaa(bbb)";
    String toString = "X";
    String text = "aaa(bbb) aaa(bbb)";
    String resultString = text.replaceAll(fromString, toString);
    System.out.println(resultString);

}
0

1 Answer 1

4

replaceAll uses regex as its first argument. Parenthesis () are used for capturing groups so need to be escaped

String fromString = "aaa\\(bbb\\)";

Since you can't modify the input String you can use Pattern.quote

String resultString = text.replaceAll(Pattern.quote(fromString), toString);

or simply String.replace could be used which doesnt use regex arguments

String resultString = text.replace(fromString, toString);
Sign up to request clarification or add additional context in comments.

3 Comments

my issue is that I read fromString from a database and the parenthesis are already embedded in the field, how to escape the parenthesis?
You could use Pattern.quote but the simplest approach seems to be to use String.replace

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.