python regular expression replacement
淡淡烟草味
淡淡烟草味 2017-05-18 10:58:52
0
2
622

Recently encountered a problem with regular expression replacement

Each piece of data in the time data is preceded by [0]= [1]= [2]= [3]= this index:

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

Because the previous index is gone for some reasons, it can only be added using regular expressions. The problem is that the amount of data in time is different

["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},}

Is there a way to automatically add the sequence [0]= [1]= [2]= [3]=

Replenish:

The wrong data are together, and the data order in time is not the same, as follows:

["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},}

Want to change it to:

["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},}
淡淡烟草味
淡淡烟草味

reply all(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)

It’s not well written, it’s funny

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template