Search code examples
javaregexback

How to work correctly with backreferences in java regex?


I have created simple demo to see how backreferences work. It is

Pattern pattern = Pattern.compile("([0-9]+)([,=]+)\\2\\1");
    Matcher matcher = pattern.matcher("2==2 5,,,,5");
    while (matcher.find()) {
        String group = matcher.group();
        System.out.println("group=" + group);
    }

The output is :

group=2==2
group=5,,,,5

Can someone explain why 5,,,,5 is matched by backreference \\2 ?


Solution

  • Matcher#group() states

    Returns the input subsequence matched by the previous match.

    On your second loop, it returns the 2nd match in your string. That is

    5,,,,5
    

    where the ([0-9]+) matches 5, the ([,=]+) matches ,,, the \\2 matches the ,, and the \\1 matches the 5.