2017-10-16 137 views
2

我有下面的字符串,我能夠抓住'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) 

我想替換值(文本1,文本2,tex3等)與由用戶提供的新的值/或通過從另一個XML讀取。 (文本,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()但後來意識到數據不是恆定的,因此尋求幫助,再次,感謝您的答覆。

任何幫助,將不勝感激。另外,如果讓,我知道如果我能改善我現在感到掠價值的方式,因爲我用正則表達式新。

+0

'anstring'是預期的結果 –

+1

所以它就像JSON,具有鍵值的對象數組,您嘗試替換值。我對嗎? –

+1

是你以前知道的字符串text1,text2,text3等嗎?還是僅僅基於這種模式放置它們?如果他們是已知的,那麼簡單地創建一個字典並將這些值映射到newText,這將被替換,並使用'.replace()替換所有。如果值已知,則可能甚至不需要在這裏。 – MohitC

回答

2

您可以通過與重新組合使用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) 

我希望這有助於。

+2

我有這個工作,通過使用這個:'ansstring = re.sub(r '(?<=:")([^(] *)',r'new \ g <1>',val1)' –

+0

因爲您的腳本也替換了引號 –

+0

感謝您指出這一點我改變了答案 –