我有一个很长的文字,其中的部分用+++括起来,我想用方括号括起来

se1 = "+++TEXT:+++ Moshe Morgenstern is on his way to the main synagogue in the center of Bnei Brak, home to a largely ultra-orthodox - or haredi - community. +++ : Bnei Brak, Tel Aviv + Jerusalem ))+++"

我想将+++中包含的文本转换为[[]],所以,

+++TEXT+++ should become [[TEXT]]

我的代码:

import re


se1 = "+++TEXT:+++ Moshe Morgenstern is on his way to the main synagogue in the center of Bnei Brak, home to a largely ultra-orthodox - or haredi - community. +++ Karte Israel mit: Bnei Brak, Tel Aviv + Jerusalem ))+++"

comments = re.sub(r"\+\+\+.*?\+\+\+", r"[[.*?]]", se1)
print(comments)

但是输出错误

[[.*?]] Moshe Morgenstern is on his way to the main synagogue in the center of Bnei Brak, home to a largely ultra-orthodox - or haredi - community. [[.*?]]
分析解答

您可以使用此:

re.sub(r'\+\+\+(.*?)\+\+\+',r'[[\1]]',se1)

由于第二个字符串中的.*?被视为纯字符串,而不是匹配字符串中.*?的替换,因此(.*?)意味着将要使用的部分保存在替换字符串中,而\1是保存的数据。