Yes, you can detect missing groups. They return as null
.
It is also not at all relevant to your actual regexp. 'missing groups' in terms of regular expressions involves something like: foo(bar(baz))?
- where the entire bar(baz)
part is optional due to the question mark, but if that entire part isn't in the string, then the group inside this optional part is a missing group, which is returned by the Matcher object as null
.
However, you don't have any missing groups. It is not possible with the regexp you have in your question. ""
(the empty string) is a correct match for the regexp [\d]*
. The empty string is, after all, '0 or more digits'. 0 digits is a valid interpretation of '0 or more'. Thus, you are not missing a group there - it's there. As an empty string.
Which you could detect if you wanted to: match.group(2)
would be .equals("")
.
Had for example from
not been how the input starts, then the regexp would simply fail to match. If you are trying to write a tool that tries to intelligently tell you which part(s) of the input string are missing, oh boy - that is an incredibly complex story that involves parsers: The tools that e.g. javac
and other language compilers use to parse text files. It's incredibly complicated, and there are multiple libraries and algorithms to go about it.
For something as simple as this you could presumably handroll it: Make regexps that would match expectable but wrong inputs and if those match, print out an error string. For more complex grammars this soon grows into an exponential mess and we're back to: Yes, it is far more complicated than it sounds, thus, academics have written many papers on the topic. There's LL(k) parsers, LALR, packrat, negative-memoizing-only packrat, and more. They have different properties; some are fast but give relatively bad syntax error info and can't handle all grammars. Others could be fed input that will cause them to take years to parse (or gigabytes of memory even for a relatively small input), and still others are really hard to actually use as a programmer (as in, to write the grammar). I don't know about your level of skill but this isn't something I'd advise for a first or even second year java programmer.