PLY lexer for numbers always returns double

痞子三分冷 提交于 2020-01-07 07:53:20

问题


I am having trouble in ply lex with int and double using the following program. DOUBLE_VAL is returned for 1 whereas i expected INT_VAL. On changing order of INT_VAL and DOUBLE_VAL functions, i get an error on decimal point. How can i resolve them ?

tokens = (
'VERSION',
'ID',
'INT_VAL',
'DOUBLE_VAL'
)

t_ignore = ' \t'
def t_VERSION(t):
    r'VERSION'
    return t

def t_DOUBLE_VAL(t):
    '[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?'
    return t

def t_INT_VAL(t):
    r'[-+]?[0-9]+'
    return t

def t_ID(t):
    r'[a-zA-Z_]([_a-zA-Z0-9]*[a-zA-Z0-9])?'
    return t

def t_error(t):
    print "Error: ", t
    #exit(-1)

import ply.lex as lex
lexer = lex.lex()
lexer.input('VERSION 1 4.0')
while True:
    tok = lexer.token()
    if not tok: break
    print tok

回答1:


Your grammar is matching integers with t_DOUBLE_VAL. Change t_DOUBLE_VAL's expression to only match if a decimal point is present:

def t_DOUBLE_VAL(t):
    '[-+]?[0-9]+(\.([0-9]+)?([eE][-+]?[0-9]+)?|[eE][-+]?[0-9]+)'
    return t


来源:https://stackoverflow.com/questions/19821234/ply-lexer-for-numbers-always-returns-double

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!