[英]how to enclose sub-string into square brackets python
我有一个很长的文本,其中的部分用 +++ 括起来,我想用方括号括起来
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)
但它给出了错误的 output
[[.*?]] 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. [[.*?]]
您需要使用()
捕获组,然后使用\1
引用该匹配组
这应该可以正常工作:
>>> comments = re.sub(r"\+\+\+(.*?)\+\+\+", r"[[\1]]", se1)
>>> comments
'[[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 ))]]'
考虑到\+\+\+
也可以简化为\+{3}
。
你可以使用这个:
re.sub(r'\+\+\+(.*?)\+\+\+',r'[[\1]]',se1)
作为.*?
在第二个字符串中被视为纯字符串而不是替换.*?
在匹配字符串中, (.*?)
表示保存这部分以用于替换字符串, \1
是保存的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.