Home > Net >  Java Matcher.group(String) throws UnsupportedOperationException on older Android versions
Java Matcher.group(String) throws UnsupportedOperationException on older Android versions

Time:02-02

I have a Java library which calls Matcher#group(String), i.e. retrieves a group from a matcher by its name.

This works in the test harness for that library, which runs on JRE 17. When I run the same code on Anbox (based on Android 7 and with an API equivalent to Java 7), I get an UnsupportedOperationException.

This exception is not mentioned in the documentation, which only has IllegalStateException (if the previous match failed or no match was attempted yet) or IllegalArgumentException (if no group by that name exists in the pattern).

CodePudding user response:

Android supports named capture groups only from API 26 onwards, which corresponds to Android 8. Once again, Android 7 is the last version which lacks this feature.

Workaround is to reference capture groups by number. Downside is that numbers can change as capture groups change. That can somewhat be alleviated by using unnamed capture groups if parentheses are just needed for grouping, but that particular group is not meant to be retrieved. Simply append ?: to the opening parenthesis, i.e. (?:expression) instead of (expression).

  • Related