【问题标题】:Python Regex - replace a string not located between two specific wordsPython Regex - 替换不在两个特定单词之间的字符串
【发布时间】:2015-04-16 12:50:53
【问题描述】:

给定一个字符串,我需要在两个给定单词之间的 not 区域中将一个子字符串替换为另一个。

例如:

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) 将临时字符串恢复为原始字符串

编辑:

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

我的具体需求是根据“:”拆分字符串,当我需要忽略“:”之间的“”括号可以链接时,唯一的承诺是打开的数量括号等于右括号的数量。

例如,在以下情况下:

input  a : <<a : b> c> : <a < a < b : b> : b> : b> : a
output [a, <<a : b> c>, <a < a < b : b> : b> : b>, a]

如果答案非常不同,我将开始另一个问题。

【问题讨论】:

  • 狼:{,鸡:},吃:a。这些是否可能:"a { a a } a""a {a} a {a} a""{a {a} }""{a} a a"?您可以编辑问题以解释更多案例吗?
  • 是的,尤其是 {a {a} },在这种情况下,这些“a”都不应更改。
  • 在 Python 中,您使用的是re 还是regex?您是否考虑过非正则表达式解决方案?
  • re,python 2.7,但同样适用于 3.4
  • 对于我评论中的所有案例(以及更多),我会冒险说你不能用 Python re 正则表达式来做到这一点。使用regex 模块,您可以进行递归(IIRC),但我不确定您是否也想去那里。写一个循环,计数{},当count0时替换。

标签: python regex


【解决方案1】:
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

【讨论】:

  • 这就是我的意思:)
【解决方案2】:

使用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'

更新:

更新的问题将通过使用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']

DEMO

【讨论】:

  • DEMO 链接不能正常工作,附上的 python 示例工作正常。
  • 是的,它只显示捕获的文本。添加只是为了显示嵌套的&lt;&gt; 是如何被捕获的。
  • 我确实发现了一个问题:a>(没有 ":" )被拆分为 ['a', '>']。我不想预先优化,但我不知道相对于定制的非正则表达式解决方案的性能如何。
  • 如果您还有任何问题,请将其作为新问题连同示例输入和预期输出一起提出。
  • 问了一个后续问题 - stackoverflow.com/questions/29727339/…
猜你喜欢
  • 2012-09-14
  • 2019-03-01
  • 2016-11-24
  • 1970-01-01
  • 2016-12-06
  • 2022-08-04
  • 2022-01-24
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多