【问题标题】:Error with re.sub (re module python3) while replacing text that are inside parethesis/square bracket [duplicate]替换括号/方括号内的文本时re.sub(re模块python3)出错[重复]
【发布时间】: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 !

https://repl.it/repls/HarmoniousMadeupBases试试这个

【问题讨论】:

标签: python regex str-replace


【解决方案1】:

用replace代替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)

【讨论】:

  • (?:.*?) = .*?
  • 这是问题的答案还是附录?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2017-11-17
  • 2019-03-10
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多