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);

}
ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

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);
Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276