[英]Python regex: substitute all occurrence of a certain string NOT after a specific character
[英]How to replace a specific character after the occurrence of a string using regex
我有一個特定的要求 - 在 python 中使用正則表達式在字符串中遇到“~”后,我需要替換所有“@”符號。
樣本輸入-
a) //div[@id='1234'] ~ div[@id='abcd'] ~ a[@href='/xyz']
b) //div[@id='1234']/div[@id='abcd'] ~ a[@href='/xyz']
所需 output -
a) //div[@id='1234'] ~ div[id='abcd'] ~ a[href='/xyz']
b) //div[@id='1234']/div[@id='abcd'] ~ a[@href='/xyz']
注意 - '~' 符號的 position 可以出現在任何地方,我們需要在遇到它后才需要更換。
我試圖創建一些正則表達式,但到目前為止還沒有成功。 有什么幫助嗎?
將正則表達式模式與兩個捕獲組一起使用:
r"(~[^@]*)(@)" # first capture group starts with ~ and excludes @
# 2nd capture group just has @
替換將第一個捕獲組保留在字符串 s
re.sub(r"(~[^@]*)(@)", r"\1", s)
例子:
print(re.sub(r"(~[^@]*)(@)", r"\1", r"//div[@id='1234'] ~ div[@id='abcd'] ~ a[@href='/xyz']")
# Output: "//div[@id='1234'] ~ div[id='abcd'] ~ a[href='/xyz']"
您也可以在沒有正則表達式的情況下執行此操作 - 在您的字符串中找到~
的索引並在該索引之后替換@
字符
s = "//div[@id='1234'] ~ div[@id='abcd'] ~ a[@href='/xyz']"
out_s = s[:s.index('~')] + s[s.index('~'):].replace('@', '')
Output
"//div[@id='1234'] ~ div[id='abcd'] ~ a[href='/xyz']"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.