用于数字的PLY词法分析器总是返回双精度 [英] PLY lexer for numbers always returns double
本文介绍了用于数字的PLY词法分析器总是返回双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用以下程序在使用int和double的lex层中遇到麻烦. DOUBLE_VAL返回1,而我预期为INT_VAL.在更改INT_VAL和DOUBLE_VAL函数的顺序时,小数点出现错误.我该如何解决?
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
推荐答案
您的语法与t_DOUBLE_VAL
匹配整数.将t_DOUBLE_VAL
的表达式更改为仅在存在小数点时才匹配:
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
这篇关于用于数字的PLY词法分析器总是返回双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文