如何在python 2.7中使用re.UNICODE?

fai*_*wle 2 python regex unicode python-2.7

我试图使用re.UNICODE标志来匹配可能包含unicode字符的字符串,但它似乎没有工作.例如:

Python 2.7.12 (default, Dec  4 2017, 14:50:18) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> r = re.compile(ur"(\w+)", re.UNICODE)
>>> r.findall(u"test test test", re.UNICODE)
[]
Run Code Online (Sandbox Code Playgroud)

它可以工作,如果我没有指定unicode标志,但显然它不适用于unicode字符串.为了让这个工作,我需要做什么?

khe*_*ood 6

第二个参数r.findall不是标志,而是pos.当您已经指定了标志时,您不需要再次指定标志compile.

>>> r = re.compile(ur"(\w+)", re.UNICODE)
>>> r.findall(u'test test test')
[u'test', u'test', u'test']
Run Code Online (Sandbox Code Playgroud)