python 正则表达式替换

最近遇到一个正则表达式替换的问题

time数据里面的每条数据前面都有[0]= [1]= [2]= [3]=这个索引:

["time"]={[0]={["status"]=true,["ac"]=1,["bg"]=2},[1]={["status"]=true,["ac"]=1,["bg"]=2},[2]={["status"]=true,["ac"]=1,["bg"]=2},}

因为一些原因前面的索引没了,只能用正则来加上,问题是time里面的数据数量是不一样的

["time"]={{["status"]=true,["ac"]=1,["bg"]=2},}
["time"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}
["time"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}

有没有方法自动在前面加顺序的[0]= [1]= [2]= [3]=

补充:

错误的数据是在一起的,而且time里面的数据顺序不相同,如下:

["time1"]={{["status"]=true,["ac"]=1,["bg"]=2},},["time2"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},},["time3"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}

想改成:

["time1"]={[0]={["status"]=true,["ac"]=1,["bg"]=2},},["time2"]={[0]={["status"]=true,["ac"]=1,["bg"]=2},[1]={["status"]=true,["ac"]=1,["bg"]=2},},["time3"]={[0]={["status"]=true,["ac"]=1,["bg"]=2},[1]={["status"]=true,["ac"]=1,["bg"]=2},[2]={["status"]=true,["ac"]=1,["bg"]=2},}
阅读 2.4k
2 个回答
>>> import re
>>> s='["time"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}'
>>> n=0
>>> def repl(m):
    global n
    rslt='[%d]=%s'%(n,m.group(0))
    n+=1
    return rslt

>>> p=re.compile(r'\{[^{}]+\},')
>>> p.sub(repl,s)
'["time"]={[0]={["status"]=true,["ac"]=1,["bg"]=2},[1]={["status"]=true,["ac"]=1,["bg"]=2},[2]={["status"]=true,["ac"]=1,["bg"]=2},}'
i = 0
def func(x):
    global i
    s = '[%d]=%s' % (i,x)
    i += 1
    return s 
import re
a = '["time"]={{["status"]=true,["ac"]=1,["bg"]=2},{["status"]=true,["ac"]=1,["bg"]=2},}'
print re.sub('\{\["status"',lambda m:func(m.group(0)),a)

写的不好,见笑了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题