code: public static CapturingGroup balancedCapture(final CharSequence path, final int startPos, final int endPos,
              final CaptureType type)
     {
        Assert.notNull(path, "Character input array must not be null.");
        Assert.assertTrue(startPos >= 0, "Start position must be greater than zero.");
        Assert.assertTrue(startPos < (path.length() - 1),
                 "Start position must be at least one character before the array upper bound.");
        Assert.assertTrue(endPos > 0, "End position must be greater than zero.");
        Assert.assertTrue(endPos < path.length(), "End position must be less than or equal to the array upper bound.");
        Assert.assertTrue(startPos < endPos, "Start position must be less than end position.");
  
        Assert.assertTrue(path.charAt(startPos) == type.getBegin(),
                 "Character at starting position was [" + path.charAt(startPos)
                          + "] but expected [" + type.getBegin() + "]");
  
        if ((startPos > 0) && (path.charAt(startPos - 1) == ESCAPE_CHAR))
        {
           if ((startPos == 1) || ((startPos > 1) && (path.charAt(startPos - 2) != ESCAPE_CHAR)))
           {
              throw new IllegalArgumentException(
                       "Character at starting position is escaped, and cannot be used in capturing a group.");
           }
        }
  
        int depth = 1;
  
        char begin = type.getBegin();
        char term = type.getEnd();
  
        int cursor = startPos + 1;
        while ((cursor < endPos) && (depth > 0))
        {
           if (path.charAt(cursor) == term)
           {
              if (!isEscaped(path, cursor))
                 depth--;
           }
           else if (path.charAt(cursor) == begin)
           {
              if (!isEscaped(path, cursor))
                 depth++;
           }
  
           if (depth == 0)
           {
              break;
           }
           cursor++;
        }
  
        return new CapturingGroup(path, startPos, cursor);
     }
docs: Return the index of the terminating character in the group, excluding markers.