Python正则表达式:除外部大括号外,搜索并替换字符

023*_*5ev 1 python regex string

我正在研究Python中的一个问题,我需要在字符串中的任何地方搜索和替换某个字符,除非它位于花括号之间.当角色位于大括号之间时,我知道如何执行此操作,但是当它位于大括号外时不知道如何执行此操作.基本上,我希望搜索跳过两个分隔符之间的任何内容.

我目前的工作是在整个字符串上执行搜索和替换,然后再次搜索并替换大括号以撤消最后一次替换的那部分.

以下是我正在寻找的功能的示例:

import re
>>> str = 'I have a _cat, here is a pic {cat_pic}. Another_pic {cat_figure}'
>>> re.sub(regex1,'/_',str)
'I have a /_cat, here is a pic {cat_pic}. Another/_pic {cat_figure}'
Run Code Online (Sandbox Code Playgroud)

我目前使用的解决方案分为两个步骤:

import re
>>> str = 'I have a _cat, here is a pic {cat_pic}. Another_pic {cat_figure}'
>>> s1 = re.sub('_','/_',str)
>>> s1
'I have a /_cat, here is a pic {cat/_pic}. Another/_pic {cat/_figure}'
>>> s2 = re.sub(r'\{(.+?)/_(.+?)\}', r'{\1_\2}', s1)
>>> s2
'I have a /_cat, here is a pic {cat_pic}. Another/_pic {cat_figure}'
Run Code Online (Sandbox Code Playgroud)

有没有办法使用正则表达式来做这个是一个语句,还是目前的两步过程是最干净的方法?

谢谢

hwn*_*wnd 5

假设所有支撑均衡,您可以尝试使用此Lookahead组合.

>>> re.sub(r'(?=_)(?![^{]*\})', '/', str)
Run Code Online (Sandbox Code Playgroud)

说明:

(?=       look ahead to see if there is:
  _       '_'
)         end of look-ahead
(?!       look ahead to see if there is not:
 [^{]*    any character except: '{' (0 or more times)
 \}       '}'
)         end of look-ahead
Run Code Online (Sandbox Code Playgroud)

regex101 demo