给定一个字符串,我需要将一个子字符串替换为位于两个给定单词之间不区域中的另一个子字符串。
例如:
substring: "ate" replace to "drank", 1st word - "wolf", 2nd word - "chicken"
input: The wolf ate the chicken and ate the rooster
output: The wolf ate the chicken and drank the rooster
目前,我唯一的解决方案是非常不干净:
1) 通过Replace a string located between 将位于两个单词之间的字符串替换为临时子字符串
2)替换我原本想要的字符串
3) 将临时字符串还原为原始字符串
编辑:
我特地问了一个与我的案例略有不同的问题,以使答案与 future 的读者相关。
我的具体需求是根据“:”拆分字符串,当我需要忽略“<”和“>”括号之间可以链接的“:”时,唯一的 promise 是打开的次数括号等于右括号的数量。
例如,在下面的情况下:
input a : <<a : b> c> : <a < a < b : b> : b> : b> : a
output [a, <<a : b> c>, <a < a < b : b> : b> : b>, a]
如果答案非常不同,我会开始另一个问题。
最佳答案
def repl(match):
if match.group()=="ate":
return "drank"
return match.group()
x="The wolf ate the chicken and ate the rooster"
print re.sub(r"(wolf.*chicken)|\bate\b",repl,x)
您可以使用替换函数来实现 re.sub
关于Python Regex - 替换不在两个特定单词之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29675262/