【发布时间】:2020-05-01 19:58:12
【问题描述】:
我没有兴趣用 {{pl|[Krzyżowa pałac]}} 替换 [Krzyżowa pałac] 以外的任何内容,但我遇到了问题,因为文本包含在 [] 中。如果文本用括号括起来,也会导致错误。
import re
text = """Hello stack community ! I just wanna replace the following line
[Krzyżowa pałac]
but there's an error if it's enclosed within parenthesis/ square bracket
Can you please help me ! PLZ
}}"""
pagetext = text
regex = r"(\[(?:.*?)\])"
matches = re.finditer(regex, text, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
Desctext = match.group(1)
Desctext = Desctext.rstrip()
lang = "pl"
new_text = "{{" + lang + "|" + Desctext + "}}"
HereIsAnError = re.sub(Desctext, new_text, pagetext, 1)
print(HereIsAnError)
我来了
Hell{{pl|[Krzyżowa pałac]}} stack community ! I just wanna replace the following line
[Krzyżowa pałac]
but there's an error if it's enclosed within parenthesis / square bracket
Can you please help me !
但我需要以下输出
Hello stack community ! I just wanna replace the following line
{{pl|[Krzyżowa pałac]}}
but there's an error if it's enclosed within parenthesis / square bracket
Can you please help me !
【问题讨论】:
-
pl 是波兰语
-
您是否有理由不只是将 re.sub 与捕获的文本一起使用,例如:repl.it/repls/ImportantLimegreenNumerators
标签: python regex str-replace