将正则表达式对象转换为可读的东西

时间:2014-04-23 17:23:24

标签: python regex dictionary

我正在尝试改变字典,以便表示正则表达式模式的值被其模式替换,例如,如果

p = dict(digit='\\d', integer='[+-]?#digit##digit#*')

然后调用expand_re(p)将返回以下字典

{'integer': '[+-]?(\\d)(\\d)*', 'digit': '\\d'}.

这是我到目前为止所拥有的

def expand_re(pat_dict:{str:str})-> None: #{names: RE pattern}    
    #Mutates dictionary by repeatedly replacing each name by its pattern in all the rules 
    # [+-]#digit##digit#*' -> '[+-]?(\\d)(\\d)*'

    for key, value in pat_dict.items():

        subbed = re.sub('#','', value)
        compiled = re.compile(subbed)
        print(compiled)
        pat_dict[key] = compiled

    return pat_dict 


pd = dict(digit=r'\d', integer=r'[=-]?#digit##digit#*')
print(expand_re(pd)) 

当我打印编译时它只打印<_sre.SRE_Pattern object at 0x026E2020>如何将整数值中的数字字符串替换为//d?这不是编译的目的吗?

0 个答案:

没有答案