python re.split() 空字符串

10S*_*Tom 5 regex python-3.x jupyter-notebook

下面的例子取自python re文档

re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
Run Code Online (Sandbox Code Playgroud)

'\b' 匹配单词开头或结尾的空字符串。这意味着如果您运行此代码,它会产生错误。

(jupyter笔记本python 3.6)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-128-f4d2d57a2022> in <module>
      1 reg = re.compile(r"\b")
----> 2 re.split(reg, "Words, word, word.")

/usr/lib/python3.6/re.py in split(pattern, string, maxsplit, flags)
    210     and the remainder of the string is returned as the final element
    211     of the list."""
--> 212     return _compile(pattern, flags).split(string, maxsplit)
    213 
    214 def findall(pattern, string, flags=0):

ValueError: split() requires a non-empty pattern match.
Run Code Online (Sandbox Code Playgroud)

由于 \b 仅匹配空字符串,因此 split() 无法满足其要求的“非空”模式匹配。我看到了与 split() 和空字符串相关的各种问题。有些我可以看到您在实践中可能想如何做到这一点,例如,这里的问题。答案各不相同,从“就是做不到”到(较老的)“这是一个错误”。

我的问题是这样的:

  1. 由于这仍然是 python 网页上的示例,这应该可行吗?这是在前沿版本中可能实现的吗?

  2. 上面链接中涉及到的问题 re.split(r'(?<!foo)(?=bar)', 'foobarbarbazbar'),是2015年提出的,只是没有办法完成要求re.split(),现在还是这样吗?

Wik*_*żew 2

Python 3.7re中,您可以使用零长度匹配进行拆分:

版本 3.7 中的更改:添加了对可以匹配空字符串的模式进行拆分的支持。

另外,请注意

仅当与先前的空匹配不相邻时,模式的空匹配才会拆分字符串。

>>> re.split(r'\b', '单词,单词,单词。')
['', '单词', ', ', '单词', ', ', '单词', '.']
>>> re.split(r'\W*', '...单词...')
['', '', '字', '', '']

>>> re.split(r'(\W*)', '...单词...') ['', '...', '', '', '字', '。 ..', '', '', '']

另外,与

re.split(r'(?<!foo)(?=bar)', 'foobarbarbazbar')


['foobar', 'barbaz', 'bar']在 Python 3.7 中得到结果。