【问题标题】:regular expression split : FutureWarning: split() requires a non-empty pattern match正则表达式拆分:FutureWarning:拆分()需要非空模式匹配
【发布时间】:2018-05-13 20:47:09
【问题描述】:

当我使用split() 命令时,我在 Python 3 版本中收到警告,如下所示:

pattern = re.compile(r'\s*')
match = re.split(pattern, 'I am going to school')
print(match)

python3.6/re.py:212: FutureWarning: split() 需要非空模式匹配。返回_编译(模式, flags).split(string, maxsplit)

我不明白为什么会收到此警告。

【问题讨论】:

    标签: regex python-3.x split


    【解决方案1】:

    您收到此警告是因为您使用 \s* 模式要求拆分 零个或多个 个空格的子字符串

    但是...空字符串与该模式匹配,因为其中有零个空格!

    目前还不清楚re.split 应该对此做什么。这就是str.split 所做的:

    >>> 'hello world'.split('')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: empty separator
    >>>
    

    re.split 决定丢弃那个空子字符串选项,而是在一个或多个空格处拆分。在 python3.6 中,它会发出你正在看到的 FutureWarning,告诉你这个决定。

    您可以通过将* 替换为+ 来自己说:

    $ python3.6 -c "import re; print(re.split('\s*', 'I am going to school'))"
    /usr/lib64/python3.6/re.py:212: FutureWarning: split() requires a non-empty pattern match.
      return _compile(pattern, flags).split(string, maxsplit)
    ['I', 'am', 'going', 'to', 'school']
    
    $ python3.6 -c "import re; print(re.split('\s+', 'I am going to school'))"
    ['I', 'am', 'going', 'to', 'school']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 2015-07-11
      • 2010-11-03
      • 2011-03-06
      相关资源
      最近更新 更多