- StringBuilder builder = new StringBuilder();
- while (template.length() > 0) {
- final Matcher matcher = openBracketOrPipe.matcher(template);
- if (matcher.find()) {
- // append to the match.
- builder.append(template.substring(0, matcher.start()));
- if (matcher.group(2) != null) { // [[
- // append to the close ]].
- final int closeIndex = template.indexOf("]]", matcher.end());
- builder.append(template.substring(matcher.start(), closeIndex + 2));
- template = template.substring(closeIndex + 2);
- } else if (matcher.group(3) != null) { // |
- result.add(builder.toString());
- builder = new StringBuilder();
- template = template.substring(matcher.end());
- } else {
- template = template.substring(matcher.start());
- assert template.length() == 0 : template;
+ int depth = 0;
+ int lastStart = 0;
+ for (int i = 1; i < template.length(); ) {
+ if (template.charAt(i) == '|' && depth == 0) {
+ final String s = template.substring(lastStart, i);
+ result.add(s.trim());
+ ++i;
+ lastStart = i;
+ } else if (template.startsWith("[[", i) || template.startsWith("{{", i)) {
+ ++depth;
+ i += 2;
+ } else if (template.startsWith("]]", i) || template.startsWith("}}", i)) {
+ --depth;
+ if (depth < 0) {
+ throw new RuntimeException("too many closings: " + template);