Python正则表达式 - 为什么字符串结尾($和\ Z)不适用于组表达式?

Pio*_*dal 12 python regex

在Python 2.6中.似乎字符串结束的标志$\Z不符合组表达式兼容.举个例子

import re
re.findall("\w+[\s$]", "green pears")
Run Code Online (Sandbox Code Playgroud)

回报

['green ']
Run Code Online (Sandbox Code Playgroud)

(所以$实际上不起作用).并使用

re.findall("\w+[\s\Z]", "green pears")
Run Code Online (Sandbox Code Playgroud)

导致错误:

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc in findall(pattern, string, flags)
    175 
    176     Empty matches are included in the result."""
--> 177     return _compile(pattern, flags).findall(string)
    178 
    179 if sys.hexversion >= 0x02020000:

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc in _compile(*key)
    243         p = sre_compile.compile(pattern, flags)
    244     except error, v:
--> 245         raise error, v # invalid expression
    246     if len(_cache) >= _MAXCACHE:
    247         _cache.clear()

error: internal: unsupported set operator
Run Code Online (Sandbox Code Playgroud)

为什么它会这样运作以及如何四处走动?

Mar*_*ers 28

[..]表达式是一个字符组,这意味着它会匹配其中所含的任何一个字符.因此,您匹配文字$字符.字符组始终应用于一个输入字符,因此永远不能包含锚点.

如果要匹配空白字符字符串结尾,请使用非捕获组,并与|或选择器结合使用:

r"\w+(?:\s|$)"
Run Code Online (Sandbox Code Playgroud)

或者,查看\b单词边界锚点.它将匹配\w组开始或结束的任何位置(因此它锚定到文本中\w字符前面或后跟\W字符的点,或者位于字符串的开头或结尾).