regex - Java replaceAll with parenthesis -


this question has answer here:

in code below i'm trying replace in text occurrences of fromstring withtostring, no replacement takes place. how set parenthesis in regex make 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);  } 

replaceall uses regex first argument. parenthesis () used capturing groups need escaped

string fromstring = "aaa\\(bbb\\)"; 

since you can't modify input string can use pattern.quote

string resultstring = text.replaceall(pattern.quote(fromstring), tostring); 

or string.replace used doesnt use regex arguments

string resultstring = text.replace(fromstring, tostring); 

Comments