2017-02-25 20 views

回答

0

考慮附加捕獲組用於第一子串打印100但 :

str = 'WALL = "W101"' 
s = re.sub(r'^(WALL =\s*)"(.*)"', r'\1"100"', str) 
print(s) 

輸出:

WALL = "100" 

\1指向第一個捕獲組withing正則表達式

+0

此外,雖然不是絕對必要在這裏,一個原始字符串也應該用於正則表達式,就像Python中的每一個正則表達式一樣。調整定義太容易了,並且突然以ASCII轉義結束,而不是正則表達式轉義,現在一切都以非直觀的方式破壞。 – ShadowRanger

+0

@ShadowRanger當然只是無意中錯過了它(只是人爲因素)。我總是使用原始字符串標記'r'...''。謝謝 – RomanPerekhrest

0

你可以使用lookbehind

import re 
str = 'WALL = "W101"' 
s = re.sub(r'(?<=WALL = ")[^"]+', '100', str) 
print(s) 

說明:

(?<=  : start lookbehind, makes sure we have the following before the match 
    WALL = " : literally 
)   : end lookbehind 
[^"]+  : 1 or more character that is NOT a double quote