【发布时间】:2015-05-25 12:27:42
【问题描述】:
我正在编写一个程序来从汇编中的源代码生成令牌,但我遇到了一个奇怪的问题。
有时代码按预期工作,有时则不然!
这是代码(变量是葡萄牙语,但我放了翻译):
import re
def tokenize(code):
tokens = []
tokens_re = {
'comentarios' : '(//.*)', # comentary
'linhas' : '(\n)', # lines
'instrucoes' : '(add)', # instructions
'numeros_hex' : '([-+]?0x[0-9a-fA-F]+)', # hex numbers
'numeros_bin' : '([-+]?0b[0-1]+)', # binary numbers
'numeros_dec' : '([-+]?[0-9]+)'} # decimal numbers
#'reg32' : 'eax|ebx|ecx|edx|esp|ebp|eip|esi',
#'reg16' : 'ax|bx|cx|dx|sp|bp|ip|si',
#'reg8' : 'ah|al|bh|bl|ch|cl|dh|dl'}
pattern = re.compile('|'.join(list(tokens_re.values())))
scan = pattern.scanner(code)
while 1:
m = scan.search()
if not m:
break
tipo = list(tokens_re.keys())[m.lastindex-1] # type
valor = repr(m.group(m.lastindex)) # value
if tipo == 'linhas':
print('')
else:
print(tipo, valor)
return tokens
code = '''
add eax, 5 //haha
add ebx, -5
add eax, 1234
add ebx, 1234
add ax, 0b101
add bx, -0b101
add al, -0x5
add ah, 0x5
'''
print(tokenize(code))
这里是预期的结果:
instrucoes 'add'
numeros_dec '5'
comentarios '//haha'
instrucoes 'add'
numeros_dec '-5'
instrucoes 'add'
numeros_dec '1234'
instrucoes 'add'
numeros_dec '1234'
instrucoes 'add'
numeros_bin '0b101'
instrucoes 'add'
numeros_bin '-0b101'
instrucoes 'add'
numeros_hex '-0x5'
instrucoes 'add'
numeros_hex '0x5'
问题是代码没有变化,有时它会给出预期的结果,但有时是这样的:
instrucoes 'add'
numeros_dec '5'
comentarios '//haha'
instrucoes 'add'
numeros_dec '-5'
instrucoes 'add'
numeros_dec '1234'
instrucoes 'add'
numeros_dec '1234'
instrucoes 'add'
numeros_dec '0'
numeros_dec '101'
instrucoes 'add'
numeros_dec '-0'
numeros_dec '101'
instrucoes 'add'
numeros_dec '-0'
numeros_dec '5'
instrucoes 'add'
numeros_dec '0'
numeros_dec '5'
问题出在哪里?
【问题讨论】:
-
总是将你的正则表达式定义为原始字符串。
-
@AvinashRaj 感谢您的提示!但仍然无法正常工作。
标签: python regex python-3.x tokenize