def METHOD_NAME(text, startpos, left, right):
  c, i = 1, startpos
  while c > 0 and i < len(text):
    if text[i:].startswith(left):
      c += 1
      i += len(left)
    elif text[i:].startswith(right):
      c -= 1
      i += len(right)
    else:
      i += 1
  if c > 0:
    raise Exception('Brackets don\'t match: could not find {0} for {1}'.format(right, left))
  return i - len(right)