我需要使用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)