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

1 投票
3 回答
1131 浏览
提问于 2025-04-18 07:14

我正在用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}'

我现在使用的解决方案是一个两步的过程,具体如下:

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}'

有没有办法用正则表达式在一个语句中完成这个操作,还是说现在的两步过程是最简洁的方法?

谢谢

3 个回答

-1

好的,这个一步到位的解决方案直接来自于 匹配(或替换)模式,除了在情况 s1, s2, s3 等等

这里有一个简单的正则表达式,我们将用它来替换正确的下划线:

{[^}]*}|(_)

OR(也就是 |)左边的表达式会匹配完整的 {大括号字符串}。我们会忽略这些匹配。右边的部分则会匹配并捕获下划线到第 1 组,我们知道这些下划线是正确的,因为它们没有被左边的表达式匹配到。

这个程序展示了如何使用这个正则表达式(可以在 在线演示的底部查看结果)。

import re
subject = 'I have a _cat, here is a pic {cat_pic}. Another_pic {cat_figure}'
regex = re.compile(r'{[^}]*}|(_)')
def myreplacement(m):
    if m.group(1):
        return ""
    else:
        return m.group(0)
replaced = regex.sub(myreplacement, subject)
print(replaced)

参考

如何匹配模式,除了在情况 s1, s2, s3

0

这里有另一种没有前瞻的解决方案:

re.sub(r'\{.*?\}|_', lambda x: '/_' if x.group(0) == '_' else x.group(0), str)
5

假设所有的括号都是配对好的,你可以试试这个 前瞻 的组合。

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

解释:

(?=       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

regex101 演示

撰写回答