Matcher.group throws IndexOutOfBoundsException Exception

Viewed 2463

I've below code and in which i am trying to print all the matches in a String using Matcher.group().

public static void main(String[] args) {
        String s = "foo\r\nbar\r\nfoo"
                + "foo, bar\r\nak  = "
                + "foo, bar\r\nak  = "
                + "bar, bar\r\nak  = "
                + "blr05\r\nsdfsdkfhsklfh";
        //System.out.println(s);
        Matcher matcher = Pattern.compile("^ak\\s*=\\s*(\\w+)", Pattern.MULTILINE)
                .matcher(s);
        matcher.find();
        // This one works
        System.out.println("first match " + matcher.group(1));
        // Below 2 lines throws IndexOutOfBoundsException
        System.out.println("second match " + matcher.group(2));
        System.out.println("third match " + matcher.group(3));

    }

Above code throws Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 2 Exception.

So My question is how Matcher.group() works and As you can see i'll have 3 matching string, how can i print all of them using the group().

2 Answers
Related