javaregexbackreference

Multiple Backreferences in Matcher.replaceAll()


Matcher.replaceAll() with a single backreference works great (i.e. Matcher.replaceAll("$2")).

But I haven't been able to make it work with two or more backreferences, e.g. Matcher.replaceAll("$1$2").

Does Matcher.replaceAll() support multiple backreferences at all? If so, what is the proper syntax to use it?


Solution

  • It works just fine. The following snippet:

    Pattern p = Pattern.compile("(.)(.)");
    Matcher m = p.matcher("ab");
    System.out.println(m.replaceAll("$2$1"));
    

    will print:

    ba