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

标签 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

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

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/

相关文章:

c# - 替换字符串正则表达式中的日期

regex - sed regex可以模拟后向和前瞻吗?

javascript - Javascript 的正则表达式后视解决方法?

python - Pandas:缩短多列的字符串

python - Pandas:将分类列分解为多列

python - 如何清理 Python 和 Flask 中用户提供的路径?

python - 当从 Upstart 运行时没有获得环境变量时,Gunicorn + Django 不起作用

python - 如何使用python删除excel中的合并行?

regex - Sed 附加正则表达式捕获组

java - Java如何获取字符串中通配符的值?