Skip to main content
 首页 » 编程设计

python 使用正则表达式搜索和更新字符串

2024年10月01日33wayfarer

我有下面的字符串,我能够获取我想要的'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) 

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

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() 但后来意识到数据不是常量。因此再次寻求帮助。感谢您的回复。

如有任何帮助,我们将不胜感激。另外,如果让我知道我是否可以改进我现在获取值(value)的方式,就像我使用正则表达式一样。

请您参考如下方法:

您可以使用 backreferences 来完成此操作结合 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>是第一个 () 中的文本.

编辑

也许更好的方法是解码字符串,更改数据并再次编码。这应该可以让您更轻松地访问这些值。

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) 

希望对您有所帮助。