Python使用Unicode正则表达式拆分行为

时间:2017-02-01 01:51:46

标签: python regex unicode

运行Python 2.7.12。

我在使用带有Unicode正则表达式的split时遇到了一些意外行为,更具体地说是涉及\w\W。 (我已经检查了其他问题并知道要包含re.UNICODE标志并将字符串写为u'whatever'。)

为简单起见,我们可以将问题归结为使用单个字符,比如я(即Python中的\u044f)。

一方面,我得到了

>>> re.match(ur'\w', u'\u044f', re.UNICODE)
<_sre.SRE_Match object at 0xb70e7528>

这就是我所期望的:я与\w匹配。

另一方面,

>>> re.split(ur'\w', u'\u044f', re.UNICODE)
[u'\u044f']

然而,基于之前的匹配,我希望此处的输出为[u'', u'']

可以使用\W翻转,如下所示:

>>> re.match(ur'\W', u'\u044f', re.UNICODE)
>>> re.split(ur'\W', u'\u044f', re.UNICODE)
[u'', u'']

再次re.match是我期望的(不匹配),但是re.split似乎做了一个关于面部的行为,就像有匹配一样。

这里发生了什么?

1 个答案:

答案 0 :(得分:0)

re.split的第三个参数是maxsplit而非flags

>>> import re
>>> help(re.split)
Help on function split in module re:

split(pattern, string, maxsplit=0, flags=0)
    Split the source string by the occurrences of the pattern,
    returning a list containing the resulting substrings.  If
    capturing parentheses are used in pattern, then the text of all
    groups in the pattern are also returned as part of the resulting
    list.  If maxsplit is nonzero, at most maxsplit splits occur,
    and the remainder of the string is returned as the final element
    of the list.

所以要么使用:

re.split(ur'\w', u'\u044f', 0, re.UNICODE)

或:

re.split(ur'\w', u'\u044f', flags=re.UNICODE)