我正在我的应用程序中构建一些模板,其中包含如下字符串:
templateString = r'{title} {- author} ({timestamp})'
并替换模板{}中相应的字符串(如果存在):
# 10 things on my todo list - Brandon (2018-01-01 00:00:01)
我想在模板字符串中允许自定义字符,这样用户就可以连字符、方括号或其他任何内容,但前提是这些属性存在,例如,如果author为空,则不希望看到:
# 10 things on my todo list - (2018-01-01 00:00:01)
你想看看:
# 10 things on my todo list (2018-01-01 00:00:01)
为此,我尝试使用捕获组来获取存在于{
(标识词)和}
之间的任何文本:
titleExp = re.compile(r'\{([^\{]*)title([^\}]*)\}', re.I)
authorExp = re.compile(r'\{([^\{]*)author([^\}]*)\}', re.I)
timestampExp = re.compile(r'\{([^\{]*)timestamp([^\}]*)\}', re.I)
最奇怪的是,当我尝试用原始字符串替换时,r'\1{}\2'
,而不是“我的待办事项列表上的10件事”,我得到了“我的待办事项列表上的H件事”:
templateString = r'{title} {- author} ({timestamp})'
self.title = "10 things on my todo list"
renamed = re.sub(titleExp, (r'\1{}\2' if self.title else '').format(self.title or ''), renamed)
# H things on my todo list ...
我当然试过了,但没有使用原始字符串:
templateString = r'{title} {- author} ({timestamp})'
self.title = "10 things on my todo list"
renamed = re.sub(titleExp, ('\\1{}\\2' if self.title else '').format(self.title or ''), renamed)
# 10 things on my todo list ...
但同样的事情也发生了。你知道吗
怎么回事?为什么原始的弦会乱作一团?我可以看出这与数字有关,很可能是捕获组的行为不正常。你知道吗
端到端复制:
templateString = r'{title} {- author} ({timestamp})'
titleExp = re.compile(r'\{([^\{]*)title([^\}]*)\}', re.I)
authorExp = re.compile(r'\{([^\{]*)author([^\}]*)\}', re.I)
timestampExp = re.compile(r'\{([^\{]*)timestamp([^\}]*)\}', re.I)
title = "10 things on my todo list"
author = "Brandon"
timestamp = "2018-01-01 00:00:01"
templateString = re.sub(titleExp, r'\1{}\2'.format(title), templateString)
templateString = re.sub(authorExp, r'\1{}\2'.format(author), templateString)
templateString = re.sub(timestampExp, r'\1{}\2'.format(timestamp), templateString)
print(templateString)
# output:
# H things on my todo list - Brandon (P18-01-01 00:00:01)
# ^ ?? ^ ??
# expected:
# 10 things on my todo list - Brandon (2018-01-01 00:00:01)
更多研究:
它似乎与替换字符串的第一个字符有关:
title = " 10 things on my todo list"
#. ^ space
author = "Brandon"
timestamp = " 2018-01-01 00:00:01"
#. ^ space
修复它。。。某种程度上。。。你知道吗
值得一提的是,如果我在不使用内联捕获组的情况下分解表达式,它的行为是正确的。我现在可以用这个作为解决办法,但我肯定会喜欢一个解释为什么。。。你知道吗
您可以将
"-"
放在{author}
占位符之外,然后使用re.sub
:输出:
当
author
为空时:输出:
相关问题 更多 >
编程相关推荐