如何使用正则表达式删除字符串上嵌套文本周围的图案文本?



我有一个文本txt = 'The fat m{cat sat} on m{the} mat.',我希望输出'The fat cat sat on the mat.'

我尝试了以下两种方法:

re.sub(r'\m{(.*)}', '', txt) 
# output: 'The fat  mat.'
re.sub(r'\m{(?=.*)}', '', txt) 
# output: 'The fat \m{cat sat} on \m{the} mat.'

为什么会这样,我该怎么办?

您可以稍微修改自己的正则表达式以使其正常工作

  • 使用反向引用替换值,而不仅仅是空字符串
  • 也让你正则表达式懒惰,即(.*) -> (.*?) or ([^}]*)

import re
txt = 'The fat m{cat sat} on m{the} mat.';
r = re.sub(r'\m{(.*?)}', "g<1>", txt);
print(r);      
//The fat cat sat on the mat.

注意:- 您可以使用r"1""\1"而不是g<1>来反向引用捕获的组

也许这个表达式

\m{|}

替换为空字符串可能有效。

测试

import re
print(re.sub(r"\m{|}", '', 'The fat m{cat sat} on m{the} mat.'))

输出

The fat cat sat on the mat.

最新更新