Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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 - Fatal编程技术网

如何在python中用正则表达式替换前缀和后缀

如何在python中用正则表达式替换前缀和后缀,python,regex,Python,Regex,我想在文本中找到一些已知的前缀和后缀,并用新的前缀和后缀替换它们,保持它们之间的原始文本不变 示例:我想将标题更改为标题 其中“标题”可以是我不知道的任何文本 我正在使用python,我发现了如何更改前缀和后缀: s = "<h1>Title</h1>" replaced = re.sub(r'(<h1>).*?(</h1>)', r'<h2>new text</h2>', s) print(replaced) s=“Ti

我想在文本中找到一些已知的前缀和后缀,并用新的前缀和后缀替换它们,保持它们之间的原始文本不变

示例:我想将
标题
更改为
标题
其中“标题”可以是我不知道的任何文本

我正在使用python,我发现了如何更改前缀和后缀:

s = "<h1>Title</h1>"
replaced = re.sub(r'(<h1>).*?(</h1>)', r'<h2>new text</h2>', s)
print(replaced)
s=“Title”
已替换=re.sub(r'()*?()',r'新文本',s)
打印(已替换)
这将打印
新文本
。 但是,如何在标签之间打印原始文本

谢谢大家!

作为,您应该使用以下组:

replaced = re.sub(r'(<h1>)(.*?)(</h1>)', r'<h2>\2</h2>', s)
replaced=re.sub(r'()(.*)(),r'\2',s)
这是您的原始正则表达式,但您不需要为前缀和后缀创建组,只有内容足够:

replaced = re.sub(r'<h1>(.*?)</h1>', r'<h2>\1</h2>', s)
replaced=re.sub(r'(.*?),r'\1',s)

阅读文档:。这称为“分组”。@anubhava:这打印的
$1
@anubhava应该是
\1
,而不是
$1
;请参见
replaced=re.sub(r'(.*?),r'\1',s)
@jornsharpe:\1在本例中为´´,因此它会打印´´´