如何将子字符串括在方括号中 python
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)
但它给出了错误的输出
[[.*?]] 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. [[.*?]]
您需要使用 ()
捕获组,然后使用 </code></p> 引用该匹配组
<p>这应该可以正常工作:</p>
<pre><code>>>> comments = re.sub(r"\+\+\+(.*?)\+\+\+", r"[[]]", 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'[[]]',se1)
由于第二个字符串中的.*?
被视为纯字符串而不是匹配字符串中.*?
的替换,(.*?)
表示将这部分保存为在替换字符串中使用,
是保存的数据。
我有一个很长的文本,其中部分包含在 +++ 中,我想用方括号括起来
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. [[.*?]]
您需要使用 ()
捕获组,然后使用 </code></p> 引用该匹配组
<p>这应该可以正常工作:</p>
<pre><code>>>> comments = re.sub(r"\+\+\+(.*?)\+\+\+", r"[[]]", 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'[[]]',se1)
由于第二个字符串中的.*?
被视为纯字符串而不是匹配字符串中.*?
的替换,(.*?)
表示将这部分保存为在替换字符串中使用,是保存的数据。