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