在Python re中仅匹配Unicode字母
我有一个字符串,我想从中提取出三个部分:
'19 janvier 2012' -> '19', 'janvier', '2012'
这个字符串中的月份名称可能包含非ASCII字符,所以用 [A-Za-z]
这个方式对我来说不太管用:
>>> import re
>>> re.search(ur'(\d{,2}) ([A-Za-z]+) (\d{4})', u'20 janvier 2012', re.UNICODE).groups()
(u'20', u'janvier', u'2012')
>>> re.search(ur'(\d{,2}) ([A-Za-z]+) (\d{4})', u'20 février 2012', re.UNICODE).groups()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
>>>
我可以使用 \w
,但它会匹配数字和下划线,这样就不符合我的需求了:
>>> re.search(ur'(\w+)', u'février', re.UNICODE).groups()
(u'f\xe9vrier',)
>>> re.search(ur'(\w+)', u'fé_q23vrier', re.UNICODE).groups()
(u'f\xe9_q23vrier',)
>>>
我尝试使用 [:alpha:],但是没有成功:
>>> re.search(ur'[:alpha:]+', u'février', re.UNICODE).groups()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groups'
>>>
如果我能找到一种方法来匹配 \w
,但不包括 [_0-9]
,我不知道该怎么做。而且即使我找到了这种方法,Python里有没有类似 [:alpha:]
的现成快捷方式呢?
1 个回答
64
你可以创建一个新的字符类别:
[^\W\d_]
而不是使用 \w
。简单来说,它的意思是“任何不是非字母数字的字符([^\W]
和 \w
是一样的),但也不是数字,也不是下划线”。
所以,这样做只会允许使用Unicode字母。