Skip to content Skip to sidebar Skip to footer

Python To Search And Update String With Regex

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 = '[{"vmdId":"Text1&qu

Solution 1:

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'(?<=:&quot;)([^(]*)', 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 versionif sys.version_info[0] < 3:
    import HTMLParser
    html = HTMLParser.HTMLParser()
    html_escape_table = {
        "&": "&amp;",
        '"': "&quot;",
        "'": "&apos;",
        ">": "&gt;",
        "<": "&lt;",
        }

    defhtml_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 = '[{&quot;vmdId&quot;:&quot;Text1&quot;,&quot;vmdVersion&quot;:&quot;text2&quot;,&quot;vmId&quot;:&quot;text3&quot;},{&quot;vmId&quot;:&quot;text4&quot;,&quot;vmVersion&quot;:&quot;text5&quot;,&quot;vmId&quot;:&quot;text6&quot;}]'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.

Post a Comment for "Python To Search And Update String With Regex"