簡體   English   中英

如何使用正則表達式在出現字符串后替換特定字符

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM