Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式删除字符串上嵌套文本周围的图案文本?_Python_Regex_Re - Fatal编程技术网

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.