首页 > 解决方案 > 可选的多行字符串替换

问题描述

我有一个长字符串,其中包含一些占位符,例如%name%应该用字典给出的值替换。根据这个链接,我能够解决它。但是,如果另一个参数为 True,则某些部分应仅包含在返回的字符串中。例如使用这种格式:

>>optional:This should only get printed, if 'optional' is True<<

我可能会让它工作,但我无法创建一个也适用于多行的正则表达式

import re 

# This works (https://stackoverflow.com/questions/26844742/advanced-string-replacements-in-python)
def replaceParameter(string, replacements):
  return re.sub('%(\w+)%', lambda m: replacements[m.group(1)], string)

# This does not work
def replaceOptionalText(myString, replacements):
  occurences = re.findall(">>(.*?):(.*)<<", myString, re.MULTILINE)
  # ... #

myLongString = r"""My name is %name%.
I want to >>eat:eat some %food%.
(in two lines)<<
>>drink:drink something<<
"""

replacements = {
  'name': 'John',
  'eat': True,
  'food': 'Apples',
  'drink': False,
}

myLongString = replaceOptionalText(myLongString, replacements)
myLongString = replaceParameter(myLongString, replacements)
print(myLongString)

与预期的输出:

My name is John.
I want to eat some Apples.
(in two lines)

标签: pythonregexstringreplace

解决方案


推荐阅读