Python Regex - 替换不在两个特定单词之间的字符串

Ere*_*ezO 7 python regex

给定一个字符串,我需要在不在两个给定单词之间的区域中用另一个子串替换子串.

例如:

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
Run Code Online (Sandbox Code Playgroud)

目前,我唯一的解决方案是非常不洁净:

1)通过替换位于其间的字符串,将位于两个单词之间的字符串替换为临时子字符串

2)替换我原来想要的字符串

3)将临时字符串还原为原始字符串

编辑:

我特别提出了一个与我的案例略有不同的问题,以保持答案与未来的读者相关.

我特别需要根据":"拆分一个字符串,当我需要忽略"<"和">"括号之间可以链接的":"时,唯一的承诺是开口括号的数量等于关闭括号的数量.

例如,在以下情况中:

input  a : <<a : b> c> : <a < a < b : b> : b> : b> : a
output [a, <<a : b> c>, <a < a < b : b> : b> : b>, a]
Run Code Online (Sandbox Code Playgroud)

如果答案非常不同,我会提出另一个问题.

Avi*_*Raj 1

使用re.sub单行函数。

>>> s = "The wolf ate the chicken and ate the rooster"
>>> re.sub(r'wolf.*?chicken|\bate\b', lambda m: "drank" if m.group()=="ate" else m.group(), s)
'The wolf ate the chicken and drank the rooster'
Run Code Online (Sandbox Code Playgroud)

更新:

更新的问题将通过使用模块来解决regex

>>> s = "a : <<a : b> c> : <a < a < b : b> : b> : b> : a"
>>> [i for i in regex.split(r'(<(?:(?R)|[^<>])*>)|\s*:\s*', s) if i]
['a', '<<a : b> c>', '<a < a < b : b> : b> : b>', 'a']
Run Code Online (Sandbox Code Playgroud)

演示版