In general, your code works for me, at least for this test call:
addBlocks("foo bar \\begin{vers}bla\\end{vers}foo bar baz \\begin{refr}bla2\\end{refr} bla");
However, your regular expression will call addBlock()
at most once because of the greedy *
quantifier. You might rather want to use the *?
quantifier:
Pattern p = Pattern.compile("\\\\begin\\{(vers|refr|block)\\}.*?\\\\end\\{(vers|refr|block)\\}");
With the *?
quantifier you’ll get two matches for the above test call.
If there is no match on some input, then m.find()
will correctly return false
and m.group()
will not be called (and thus won’t throw any IllegalStateException
). Independent of the input string, m.groupCount()
will always be 2 for your particular regular expression, as there are 2 capturing groups in the pattern.