python使用regex搜索和更新字符串

2024-10-04 01:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的字符串,我能够抓住'text'我想要的(文本是扭曲之间的模式)。代码如下:

val1 = '[{"vmdId":"Text1","vmdVersion":"text2","vmId":"text3"},{"vmId":"text4","vmVersion":"text5","vmId":"text6"}]'


temp = val1.split(',')
list_len =  len(temp)

for i in range(0, list_len):
    var = temp[i]
    found = re.findall(r':"([^(]*)\&quot\;', var)
    print ''.join(found)

我想将值(Text1、text2、tex3等)替换为用户/或从另一个XML读取提供的新值。(文本1,文本2。。是完全随机的字母数字数据。下面是一些细节

Text1 = somename
text2 = alphanumatic value
text3 = somename

Text4 = somename
text5 = alphanumatic value
text6 = somename

    anstring =
 [{"vmdId":"newText1","vmdVersion":"newtext2","vmId":"newtext3"},{"vmId":"newtext4","vmVersion":"newtext5","vmId":"newtext6"}]

我决定使用replace(),但后来意识到数据不是常量。因此再次寻求帮助。感谢您的回复。你知道吗

任何帮助都将不胜感激。另外,如果让我知道,如果我可以改进的方式,我抓住价值现在,因为我与regex的新。你知道吗


Tags: 文本lentempval1text1quottext2text3
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:07

您可以将backreferences与回复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>是第一个()中的文本。你知道吗

编辑

也许更好的方法是解码字符串,更改数据并再次编码。这将使您更容易访问这些值。你知道吗

import sys

# python2 version
if sys.version_info[0] < 3:
    import HTMLParser
    html = HTMLParser.HTMLParser()
    html_escape_table = {
        "&": "&amp;",
        '"': "&quot;",
        "'": "&apos;",
        ">": "&gt;",
        "<": "&lt;",
        }

    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 = '[{&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)

我希望这有帮助。你知道吗

相关问题 更多 >