【发布时间】:2019-01-27 17:56:54
【问题描述】:
以下示例取自python re documents
re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
'\b' 匹配单词开头或结尾的空字符串。这意味着如果您运行此代码,它会产生错误。
(jupyter notebook 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.
由于 \b 仅匹配空字符串,因此 split() 无法满足其要求的“非空”模式匹配。我看到了与 split() 和空字符串相关的各种问题。有些我可以看到您在实践中可能希望如何做到这一点,例如问题here。答案从“只是做不到”到(较早的)“这是一个错误”。
我的问题是这样的:
既然这仍然是python网页上的一个例子,这应该是可能的吗?这在最前沿的版本中是可能的吗?
上面链接中的问题涉及
re.split(r'(?<!foo)(?=bar)', 'foobarbarbazbar'),2015年就问过了,光用re.split()是没有办法完成要求的,现在还是这样吗?
【问题讨论】:
-
你想在单词的开头分割吗?抱歉,与
\b分开没有多大意义。请注意,在 Python 3.7 中,您可以使用零长度匹配进行拆分。 -
更多的是关于拆分空字符串。链接中的另一个问题是否可以使用 Python 3.7。我使用了 \b 示例,因为它在网页上,并建议这种类型的事情应该是可能的。尽管拆分 \b 可能不切实际,但您想在空匹配上拆分长字符串的情况似乎很有用。这个例子因为同样的原因失败了:re.split(r'(?
-
用这个来分割单词 r"\b\W+\b" 和这个来模仿(不精确地)\b example r"(\b\W+\b)"
-
我在 Python 3.7 中得到了
['foobar', 'barbaz', 'bar']和re.split(r'(?<!foo)(?=bar)', 'foobarbarbazbar'。 -
酷,猜猜这两个答案。最前沿 (3.7) 一切皆有可能。
标签: regex python-3.x jupyter-notebook