[英]Python Regex - replace a string not located between two specific words
给定一个字符串,我需要在不在两个给定单词之间的区域中替换另一个子字符串。
例如:
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)通过替换位于其间的字符串,将位于两个单词之间的字符串替换为临时子字符串
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]
如果答案非常不同,我会提出另一个问题。
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
使用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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.