Search code examples
javaregexreplaceall

ReplaceAll replaces only first occurance of substring


I would like to replace " inside first brackets with '. Substring inside second brackets should remain unchanged. Example:

String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")"; //wanted output is ('test1', 'test2') ("test3", "test4")
String regex = "(^[^\\)]*?)\"(.*?)\"";
test = test.replaceAll(regex, "$1'$2'");
System.out.println(test); // output is ('test1', "test2") ("test3", "test4")
test = test.replaceAll(regex, "$1'$2'");
System.out.println(test); // output is ('test1', 'test2') ("test3", "test4")

Why " around test2 are not replaced during first call of replaceAll?


Solution

  • This is the good use-case to use boundary matcher \G:

    String test = "(\"test1\", \"test2\") (\"test3\", \"test4\")";
    final String regex = "(^\\(|\\G(?!^),\\h*)\"([^\"]+)\"";
    
    test = test.replaceAll(regex, "$1'$2'");
    System.out.println(test);
    //=> ('test1', 'test2') ("test3", "test4")
    

    \G asserts position at the end of the previous match or the start of the string for the first match

    RegEx Demo