'Strips unmatched BibTeX syntax'

def stripUnmatchedSyntax(self, text, open_character, close_character):

    stack = []
    assert ((len(open_character) == 1) and (len(close_character) == 1))
    remove = []
    for (i, ch) in enumerate(text):
        if (ch == open_character):
            stack.append(i)
        elif (ch == close_character):
            try:
                stack.pop()
            except IndexError:
                remove.append(i)
    remove.extend(stack)
    if remove:
        text = list(text)
        for i in sorted(remove, reverse=True):
            text.pop(i)
        text = ''.join(text)
    return text
