2

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().

kevinarpe
  • 17,685
  • 21
  • 107
  • 133
  • Does this answer your question? [Identifying capture groups in a Regex Pattern](https://stackoverflow.com/questions/4589643/identifying-capture-groups-in-a-regex-pattern) – Booboo Dec 01 '19 at 17:18
  • @Booboo: Yes, but indirectly. – kevinarpe Dec 07 '19 at 04:21

1 Answers1

4

I know method Matcher.groupCount() exists, but it requires a valid input string.

No, it doesn't.

The following has been tested on Java 7 and Java 13:

Pattern p = Pattern.compile("(x)y(z)");
Matcher m = p.matcher("");
System.out.println(m.groupCount()); // prints: 2

As you can see, you don't even have to call find() or matches() first, but you do have to create the Matcher instance.

Is there a way to access the number of capturing groups without an instance of Matcher?

Not in plain Java, i.e. without using reflection.

Andreas
  • 138,167
  • 8
  • 112
  • 195