1

I have a string, in which I want to swap chars/digits between '@' sign. For example I want
"aaa@bbb eee7@kkk" to be "bbb@aaa kkk@eee7", but when I want to address first group in my code using \1 nothing is working and if I swap it with \w+ everything works fine. I can make it work (using \w+) but I want to know why \1 don't work here.

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class Test
{
    public static void main(String[] args)
    {
        Pattern pattern1 = Pattern.compile("(\\w+)@(\\1)"); // if I swap \\1 with \\w+ everything would be fine
        Matcher matcher1 = pattern1.matcher("aaa@bbb eee7@kkk");
        System.out.println(matcher1.replaceAll("$2@$1"));
    }
}
Denys_newbie
  • 1,140
  • 5
  • 15

0 Answers0