替换括号/方括号内的文本时,re.sub(模块python3)出现错误。>

问题描述 投票:0回答:1

我不愿意将[[KrzyKowapałac]

以外的任何内容替换为{{pl | [Krzyżowapał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 !

https://repl.it/repls/HarmoniousMadeupBases尝试此>]

我不愿意用{{pl | [Krzyżowapałac]}替换[Krzyżowapałac]以外的任何内容,但是我遇到了问题,因为该文本包含在[]中。如果文本为...

python regex str-replace
1个回答
0
投票

感谢Mark Meyer

,更新的版本在这里。 !!!
© www.soinside.com 2019 - 2024. All rights reserved.