-1

I am not interested in replacing anything other than [Krzyżowa pałac] with {{pl|[Krzyżowa pałac]}}, But I am facing issues because the text is enclosed within [] . It also causes errors if the text is enclosed withing parenthesis.

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)

I am getting

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 !

But I neee the following output

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 !

Try this at https://repl.it/repls/HarmoniousMadeupBases

1 Answers1

0

Use replace instead of re.sub

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 + "}}"

HereWasAnError = pagetext.replace(Desctext, new_text, 1)

print(HereWasAnError)