I want to split an input string into blocks starting with \begin{<word>}
and ending with \end{<word>}
where <word> can be "block", "vers" or "refr" and do addBlock() on each block. When trying this method on a string containing two of these blocks, m.groupCount()
correctly returns 2, but m.find()
returns false. How can this be? m.group()
throws an exception.
private void addBlocks(String in) {
Pattern p = Pattern.compile("\\\\begin\\{(vers|refr|block)\\}.*\\\\end\\{(vers|refr|block)\\}");
Matcher m = p.matcher(in);
while (m.find()) {
addBlock(m.group());
}
}
Edit: Yep, there were several things wrong there. Regex is a pain in the ass, it isn't very intuitive, and there is not that much sensible help online. Here is the code that finally worked:
private void addBlocks(String in) {
Pattern p = Pattern.compile("\\\\begin\{(block|vers|refr)\\}(.|$)*?\\\\end\\{(block|vers|refr)\\}", Pattern.DOTALL);
Matcher m = p.matcher(in);
while (m.find()) {
addBlock(m.group());
}
}