Python正则表达式-替换不位于两个特定单词之间的字符串
给定一个字符串,我需要用位于两个给定单词之间的区域not中的另一个子字符串替换该子字符串 例如:Python正则表达式-替换不位于两个特定单词之间的字符串,python,regex,Python,Regex,给定一个字符串,我需要用位于两个给定单词之间的区域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 目前,我唯一的解决办法是非常
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]
输入a::b>:b>:a
输出[a,: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']
>>s=“a:wolf:{
,chicken:}
,ate:a
。这些都是可能的:“a{a}a”
,“a{a}a{a}a”
,“{a{a}a}a}a}”你能编辑这个问题来解释更多的情况吗?是的,尤其是在这种情况下,应该更改。在Python中,您使用的是re
还是regex
?你考虑过非正则表达式的解决方案吗?是的,python 2.7,但同样适用于3.4。在我的评论中的所有情况下(以及更多),我会冒险说你不能用pythonre
正则表达式。使用regex
模块,您可以使用递归(IIRC),但我不确定您是否也想使用它。写一个循环,计数{
和}
,当计数为0
时替换。这就是我的意思:)演示链接工作不正常,附带的python示例工作得很好。是的,它只显示捕获的文本。添加只是为了显示嵌套的
是如何被捕获的。我确实发现了一个问题:a(否):“)被拆分为['a','']。我不想预优化,但我不知道与定制的非正则表达式解决方案相比,性能如何。如果您还有任何其他问题,请将其作为新问题与示例输入和预期输出一起提问。询问后续问题-