简体   繁体   中英

How should I add quote to it which match using python re?

I have a string, like this:

{"content":(uint64)123456, "id":(uint32)0}

Note:

this example string is simple, the real string is JSON except (uint32)0 is not standard.

Now I need to transform it like this:

{"content":"(uint64)123456", "id":"(uint32)0"}

so, I write transform code with python re:

def format():
    pattern = re.compile(r'(\(uint32\)|\(int32\)|\(uint64\)|\(int64\))(\d)+')
    print pattern.sub('\"test\"', '{"content":(uint64)123456, "id":(uint32)0}')

How I should write code in sub function in order to tansform it?

Instead of a string, sub function can accept also a callable as replacement.

So, instead of:

pattern.sub('\"test\"', s)

Make a function:

def add_quotes(match):
    return '"%s"' % match.group(0)

pattern.sub(add_quotes, s)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM