I want to validate the number of capturing groups in an instance of Pattern
. I know method Matcher.groupCount()
exists, but it requires a valid input string.
Is there a way to access the number of capturing groups without an instance of Matcher
?
My current hack uses reflection to access the package-private field Pattern.capturingGroupCount
, but this is terrible for many reasons.
Field f = Pattern.class.getDeclaredField("capturingGroupCount");
int capturingGroupCount = (int) f.get(pattern);
I use Java 9+, so it is not possible -- that I know -- to create a helper method in package java.util.regex
to access package-private field capturingGroupCount
. (The Java compiler complains that package java.util.regex
is already defined in module java.base
.)
Final thought / opinion: I am surprised the Java API does not expose this member, e.g., int capturingGroupCount()
.