【发布时间】:2018-02-03 03:57:33
【问题描述】:
我在 Kaggle 内核中遇到了这个正则表达式,但不知道它的作用:
import re
def substitute_repeats_fixed_len(text, nchars, ntimes=3):
return re.sub(r"(\S{{{}}})(\1{{{},}})".format(nchars, ntimes-1),
r"\1", text)
我一直在尝试它,但发现它非常难以解释。
“一开始,调试的难度是编写代码的两倍。因此,如果你尽可能巧妙地编写代码,那么根据定义,你就不够聪明,无法调试它”。 - 布赖恩·克尼汉
【问题讨论】:
-
来自the docs:
Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}. -
好的,感谢您指出这一点。也许一些花括号是为了成为文字,但即使是这样,我仍然没有破解代码。子例程的名称表明替换应该删除重复的字符串,我想知道嵌套大括号是否不允许灵活定义被删除模式的重复次数。但这只是一个猜测。这个正则表达式太聪明了,没有提供代码cmet来解释它的作用。
-
您是否尝试过仅打印字符串或生成的正则表达式对象?
标签: python nested string-formatting curly-braces