gpt4 book ai didi

python - 为什么 Python 的 `re.split()` 不在零长度匹配上拆分?

转载 作者:太空狗 更新时间:2023-10-29 16:54:08 24 4
gpt4 key购买 nike

Python 中(否则相当强大的)re 模块的一个特别的怪癖是 re.split() will never split a string on a zero-length match ,例如,如果我想沿单词边界拆分字符串:

>>> re.split(r"\s+|\b", "Split along words, preserve punctuation!")
['Split', 'along', 'words,', 'preserve', 'punctuation!']

代替

['', 'Split', 'along', 'words', ',', 'preserve', 'punctuation', '!']

为什么会有这个限制?是设计使然吗?其他正则表达式风格是否表现得像这样?

最佳答案

这是一个已经做出的设计决定,并且可以采用任何一种方式。蒂姆·彼得斯制作 this post解释:

For example, if you split "abc" by the pattern x*, what do you expect? The pattern matches (with length 0) at 4 places, but I bet most people would be surprised to get

['', 'a', 'b', 'c', '']

back instead of (as they do get)

['abc']

但也有人不同意他的看法。吉多范罗森 doesn't want it changed由于向后兼容性问题。他做了say :

I'm okay with adding a flag to enable this behavior though.

编辑:

有一个workaround Jan Burgy 发表:

>>> s = "Split along words, preserve punctuation!"
>>> re.sub(r"\s+|\b", '\f', s).split('\f')
['', 'Split', 'along', 'words', ',', 'preserve', 'punctuation', '!']

其中 '\f' 可以替换为任何未使用的字符。

关于python - 为什么 Python 的 `re.split()` 不在零长度匹配上拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com