python to search and update string with regex

前端 未结 1 1887
囚心锁ツ
囚心锁ツ 2021-01-22 17:18

I have below string, I am able to grab the \'text\' what I wanted to (text is warped between pattern). code is give below,

val1 = \'[{"vmd         


        
1条回答
  •  情歌与酒
    2021-01-22 18:03

    You can do this by using backreferences in combination with re.sub:

    import re
    val1 = '[{"vmdId":"Text1","vmdVersion":"text2","vmId":"text3"},{"vmId":"text4","vmVersion":"text5","vmId":"text6"}]'
    
    ansstring = re.sub(r'(?<=:")([^(]*)', r'new\g<1>' , val1)
    
    print ansstring
    

    \g<1> is the text which is in the first ().

    EDIT

    Maybe a better approach would be to decode the string, change the data and encode it again. This should allow you to easier access the values.

    import sys
    
    # python2 version
    if sys.version_info[0] < 3:
        import HTMLParser
        html = HTMLParser.HTMLParser()
        html_escape_table = {
            "&": "&",
            '"': """,
            "'": "'",
            ">": ">",
            "<": "<",
            }
    
        def html_escape(text):
            """Produce entities within text."""
            return "".join(html_escape_table.get(c,c) for c in text)
    
        html.escape = html_escape
    else:
        import html
    
    import json
    
    val1 = '[{"vmdId":"Text1","vmdVersion":"text2","vmId":"text3"},{"vmId":"text4","vmVersion":"text5","vmId":"text6"}]'
    print(val1)
    
    unescaped = html.unescape(val1)
    json_data = json.loads(unescaped)
    for d in json_data:
        d['vmId'] = 'new value'
    
    new_unescaped = json.dumps(json_data)
    new_val = html.escape(new_unescaped)
    print(new_val)
    

    I hope this helps.

    0 讨论(0)
提交回复
热议问题