Parentheses pairing ({}[]()<>) issue

前端 未结 9 1572
醉酒成梦
醉酒成梦 2021-02-06 00:27

I want to be able to pair up all parentheses in a string, if they aren\'t paired then then they get their index number and False. It seems like it is repeating some values over

9条回答
  •  暖寄归人
    2021-02-06 00:45

    Thanks hughdbrown your code was a breeze to get working and it's really short! You've just saved me a headache :D

    converted it to pep8 if thats ok :)

    Edit

    • Added support for comments and strings, it will not match inside them.
    • Added support for easy language brace checking, modify the charset dict.
    • Correctly paires up, i.e right to left

    HTML

    charset = dict(opening='{[(<',\
        closing='}])>',\
        string = ('"', "'"),\
        comment=(('')))
    

    Python

    charset = dict(opening='{[(<',\
        closing='}])>',\
        string = ('"', "'"),\
        comment=(("'''", "'''"), ('"""', '"""'), ('#', '\n')))
    

    C++

    charset = dict(opening='{[(<',\
        closing='}])>',\
        string = ('"', "'"),\
        comment=(('/*', '*/'), ('//', '\n')))
    

    you get the point? :)

    charset = dict(opening='{[(<',\
        closing='}])>',\
        string = ('"', "'"),\
        comment=((''), ('"""', '"""'), ('#', '\n')))
    
    allowed = ''.join([x[0][0] + x[1][0] for x in charset['comment']])
    allowed += ''.join(charset['string'])
    allowed += charset['opening']
    allowed += charset['closing']
    
    def brace_check(text):
        o = []
        c = []
        notr = []
        found = []
        busy = False
        last_pos = None
        for i in xrange(len(text)):
            ch = text[i]
            if not busy:
                cont = True
                for comment in charset['comment']:
                    if ch == comment[0][0]:
                        como = text[i:len(comment[0])]
                        if como == comment[0]:
                            busy = comment[1]
                            if ch in charset['opening']:
                                last_pos = i
                            cont = False
                            break
                if cont:
                    if ch in charset['string']:
                        busy = ch
                    elif ch in charset['opening']:
                        o.append((ch, i))
                    elif  ch in charset['closing']:
                        c.append((ch, i))
            else:
                if ch == busy[0]:
                    if len(busy) == 1:
                        comc = ch
                    else:
                        comc = text[i:i + len(busy)]
                    if comc == busy:
                        if last_pos is not None:
                            if busy[-1] in charset['closing']:
                                found.append((last_pos, i))
                            last_pos = None
                            text = text[:i] + '\n' * len(comc) +\
                                text[i + len(comc):]
                        busy = not busy
                elif busy in charset['string']:
                    if ch == '\n':
                        busy = not busy
        for t, e in reversed(o):
            try:
                n = next((b, v) for b, v in c\
                    if b == charset['closing'][\
                        charset['opening'].find(t)] and v > e)
                c.remove(n)
                n = n[1]
                if found != []:
                    if e < found[-1][0] and n > found[-1][0] and n < found[-1][1]\
                    or e < found[-1][1] and n > found[-1][1] and e > found[-1][0]:
                        found.append((n, False))
                        n = False
            except StopIteration:
                n = False
            found.append((e, n))
        for t, e in c:
            found.append((e, False))
        return found
    

提交回复
热议问题