Python中的括号匹配

时间:2013-11-14 08:54:16

标签: python regex python-2.7 sympy

我有以下方式的字符串。我需要从下一个状态中提取字符串并添加匹配 插入语。我们是否在Python中具有可以在Python中进行括号匹配的函数

a) data = [next_state=((!SE&((A1&A2)|(B1&B2)))|(SE&SI))):Q=iq]

b) data = [(next_state=(!SE&((!B2&D)|(B2&lq))|(SE&SI)),clear=B2&lqn,preset=B2&lq)))]

data_1 = data[0].split(',')
for item in data_1:
    if item.find('next_state=')!= -1:
        item_list = item.split('=')
        item_op = item_list[len(item_list) -1].lstrip('(').rstrip(')')
        item_op = "(" + item_op + ")"
        print item_op

Excepted:((!SE&((A1&A2)|(B1&B2)))|(SE&SI))(删除额外和匹配模式)

  

如果要求正确/添加缺少的parenthisis

当我没有额外的括号时,代码工作正常。但有时它可以添加额外的括号,例如b case。所以这不是一般化的解决方案。是否可以匹配括号。

<小时/> 我根据我从下面回答得到的反馈编辑问题。最终版本的代码。谢谢提供输入。欢迎使用代码评论

#!/usr/bin/env py
import itertools
import sys
import sympy
import re
def extract_next_state(s):
    p = re.compile('(\()|(\))')
    depth = 0
    startindex = None
    start_point = False
    for m in p.finditer(s):
        if m.group(1):          # (
            depth += 1
            print "depth (", depth
            if not start_point:
                startindex = m.start()
                start_point = True
        elif m.group(2):          # )
            depth -= 1
            print "depth )", depth
            if depth == 0:
                return s[startindex:m.end()]

if __name__ == "__main__":
    #data = ['next_state=(~SE&((~B2&D)|(B2&lq))|(SE&SI))']
    data = ['next_state=((~SE&((A1&A2)|(B1&B2)))|(SE&SI)))']
    data_1 = data[0].split(',')
    com = None
    for item in data_1:
        if item.find('next_state=')!= -1:
            item_list = item.split('=')
            item_op = extract_next_state(item_list[1])
            print item_op
            expr = sympy.sympify(item_op)
            temp_list = [ str(data) for data in expr.free_symbols]
            print temp_list

1 个答案:

答案 0 :(得分:1)

import re

def extract_next_state(s):
    p = re.compile('(next_state=)|(\()|(\))')
    depth = 0
    startindex = None
    for m in p.finditer(s):
        if m.group(1):            # next_state=
            startindex = m.end()
        elif startindex is None:  # haven't found 'next_state=' yet
            continue
        elif m.group(2):          # (
            depth += 1
        elif m.group(3):          # )
            depth -= 1
            if depth == 0:
                return s[startindex:m.end()]
            elif depth < 0:
                return s[startindex:m.start()]
    if startindex is None: return None
    return s[startindex:] + ')' * depth

a = '[(next_state=(!SE&((!B2&D)|(B2&lq))|(SE&SI'
print(extract_next_state(a))
b = '[(next_state=(!SE&((!B2&D)|(B2&lq))|(SE&SI)),clear=B2&lqn,preset=B2&lq)))]'
print(extract_next_state(b))

<强>输出:

(!SE&((!B2&D)|(B2&lq))|(SE&SI))
(!SE&((!B2&D)|(B2&lq))|(SE&SI))