<分区>
我需要使用 ply 从正则表达式制作 AST。 例如,如果 RE 是 (a|b*)abc,我想将一个简化的元组作为 (':', (':', (':', ('|', 'a', ('* ', 'b')), 'a'), 'b'), 'c') <-- ':' 表示将字符串分成两部分。
这是我的代码。
tokens = (
"SYMBOL",
"LBRACKET",
"RBRACKET",
"STAR",
"UNION"
)
t_ignore = ' \t\n'
t_SYMBOL = r'[a-zA-Z0-9]'
t_LBRACKET = r'\('
t_RBRACKET = r'\)'
t_STAR = r'\*'
t_UNION = r'\|'
def t_error(t):
raise TypeError("Unknown text '%s'" % t.value)
def p_multiple(p) :
'''string : SYMBOL SYMBOL
| string SYMBOL
| string string'''
p[0] = (':', p[1], p[2])
def p_union(p) :
'''string : string UNION string'''
p[0] = ('|', p[1], p[3])
def p_star(p) :
'''string : string STAR'''
p[0] = ('*', p[1])
def p_brackets(p) :
'''string : LBRACKET string RBRACKET'''
p[0] = p[2]
def p_symbol(p) :
'''string : SYMBOL'''
p[0] = p[1]
def p_error(p):
print ("Syntax error at '%s'" % p.value)
lex.lex()
yacc.yacc()
lex.input("(a|b*)abc")
parsed = yacc.parse(RE)