I need to know, based on the regex itself (without any sample data), what the maximum number of fields it could find is.
For example, for the expression
"^(ABC) ?([0-9]{4}|[0-9]{6})?(?:(?:/)([0-9]{4}|[0-9]{6}))?(?:(?: ?XYZ ?)([0-9]{4}))?$"
I’d like some function that would take that as a String (or a Pattern) and return 4, and would take
"^(DEF) ?([0-9A-Z]{1,2})(?:(?:/)([0-9A-Z]{1,2}))?$"
and return 3.
It would be simpler if all of these groups were captured, but not all are, and I’d like to avoid having to write my own parser if possible.
This is very ugly but… seems to do what you need:
Or to add the non-reflective version, which depends on
.matcher(String)being able to reach into thePatternclass: