简体   繁体   English

如何使用正则表达式在出现字符串后替换特定字符

[英]How to replace a specific character after the occurrence of a string using regex

I have a specific requirement- I need to replace all '@' symbols after a '~' is encountered in a string using regular expression in python.我有一个特定的要求 - 在 python 中使用正则表达式在字符串中遇到“~”后,我需要替换所有“@”符号。

Sample inputs -样本输入-

a) //div[@id='1234'] ~ div[@id='abcd'] ~ a[@href='/xyz']

b) //div[@id='1234']/div[@id='abcd'] ~ a[@href='/xyz']

Desired output -所需 output -

a) //div[@id='1234'] ~ div[id='abcd'] ~ a[href='/xyz']

b) //div[@id='1234']/div[@id='abcd'] ~ a[@href='/xyz']

Note- The position of the '~' symbol can appear anywhere and we need to replace only after it has been encountered.注意 - '~' 符号的 position 可以出现在任何地方,我们需要在遇到它后才需要更换。

I have tried to create a few regex but not been successfull so far.我试图创建一些正则表达式,但到目前为止还没有成功。 Any help?有什么帮助吗?

Use regex pattern with two capture groups:将正则表达式模式与两个捕获组一起使用:

r"(~[^@]*)(@)"   # first capture group starts with ~ and excludes @
                 # 2nd capture group just has @

Substitution keeps first capture group in string s替换将第一个捕获组保留在字符串 s

re.sub(r"(~[^@]*)(@)", r"\1", s)

Example:例子:

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']"

You can do it without regexes too - find the index of ~ in your string and replace @ characters after that index您也可以在没有正则表达式的情况下执行此操作 - 在您的字符串中找到~的索引并在该索引之后替换@字符

s = "//div[@id='1234'] ~ div[@id='abcd'] ~ a[@href='/xyz']"
out_s = s[:s.index('~')] + s[s.index('~'):].replace('@', '')

Output Output

"//div[@id='1234'] ~ div[id='abcd'] ~ a[href='/xyz']"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM