Python 如何使用正则表达式删除字符串上嵌套文本周围的图案文本?
我有一个文本Python 如何使用正则表达式删除字符串上嵌套文本周围的图案文本?,python,regex,re,Python,Regex,Re,我有一个文本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.' 这是为什么?我该怎么做?也许是这
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.'
这是为什么?我该怎么做?也许是这个表达式
\\m{|}
替换为空字符串可能有效
试验
输出
您可以稍微修改自己的正则表达式以使其工作
- 使用backreference替换值,而不仅仅是空字符串
- 也会使您的正则表达式变懒,即
(.*)->(.*)或([^}]*)
重新导入
txt='The fat\m{cat sat}on\m{The}mat';
r=re.sub(r'\\m\{(.*?\}',“\g”,txt);
印刷品(r);
//肥猫坐在垫子上。
注意:-您可以使用
r“\1”
或“\\1”
而不是\g
来反向引用捕获的组,该组将删除所有}
:但是,不仅仅是\m{…}
中使用的组,我可以问一下“\g”是什么意思吗?@Tengerye是反向引用捕获的组,@Tengerye是一个相关问题,你也可以读这个
import re
print(re.sub(r"\\m{|}", '', 'The fat \m{cat sat} on \m{the} mat.'))
The fat cat sat on the mat.
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.