Skip to content

Solution – java.lang.IndexOutOfBoundsException: No group 1

Solution – java.lang.IndexOutOfBoundsException: No group 1 example shows what this exception is and how to solve or fix it when using regex.

When java.lang.IndexOutOfBoundsException: No group 1 is thrown?

This exception is thrown when we try to access the group by a number that does not exist. As the message itself says, there is no group captured by the specified number.

There could be several reasons for this exception to occur. The most common of them is trying to fetch the matched group by a number that is greater than the total groups defined by the matcher object’s pattern.

See below example when we try to fetch a group by the number, but our pattern did not specify that many groups to be matched.

Output

A regex group is defined using the opening and closing parenthesis, i.e. “(‘ and ‘)”. In the above example, the pattern defined only one group, but we tried to fetch the group number 2. That caused the “java.lang.IndexOutOfBoundsException: No group 2” exception.

Sometimes the pattern is very complicated dealing with many nested groups. In that case, you can use the groupCount method of the Matcher class to know how many groups are captured.

This method returns the number of groups in the specified pattern.

Output

Solution:

Basically, if you try to access the group by a number that is greater than the total group count, Java throws this exception. Make sure you are using the correct group number to solve.

Are you using regex lookahead or lookbehind expressions?

Sometimes the regex pattern defines a lookahead or lookbehind expression and we confuse it with a group and try to access using the group method.

Positive and negative lookahead expressions are defined using (?=RegEx), and (?!RegEx) expressions respectively. Similarly, the positive and negative lookbehind expressions are defined using (?<=RegEx), and (?<!RegEx) expressions respectively.

Have a look at the below given example that tries to extract the digit 0 that is followed by the digit 1 using a positive lookahead expression.

Output

If we try to access the above-given lookahead expression as a group, Java throws the same exception.

Output

Solution:

As you can see from the output, the total number of groups in the matcher object’s pattern is 0. The lookahead and lookbehind expressions are not groups and cannot be fetched using the group method.

If you want to learn more about regex, please visit the Java regex tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.