31

我有一个字符串,我想从中提取 3 个组:

'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],但我不知道如何。即使我知道如何做到这一点,是否有一个现成的快捷方式,如[:alpha:]在 Python 中有效?

4

1 回答 1

61

您可以构造一个新的字符类:

[^\W\d_]

而不是\w. 翻译成英文,它的意思是“任何不是非字母数字字符([^\W]与 相同\w),但也不是数字且不是下划线的字符”。

因此,它将只允许 Unicode 字母(如果您使用re.UNICODE编译选项)。

于 2012-01-19T09:52:59.220 回答