【问题标题】:python re.split() empty stringpython re.split() 空字符串
【发布时间】: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。答案从“只是做不到”到(较早的)“这是一个错误”。

我的问题是这样的:

  1. 既然这仍然是python网页上的一个例子,这应该是可能的吗?这在最前沿的版本中是可能的吗?

  2. 上面链接中的问题涉及 re.split(r'(?&lt;!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'(?&lt;!foo)(?=bar)', 'foobarbarbazbar'
  • 酷,猜猜这两个答案。最前沿 (3.7) 一切皆有可能。

标签: regex python-3.x jupyter-notebook


【解决方案1】:

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

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

另外,请注意

模式的空匹配仅在与前一个空匹配不相邻时才拆分字符串。

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

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

还有,用

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


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2013-12-09
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    相关资源
    最近更新 更多