【发布时间】:2012-02-13 23:42:28
【问题描述】:
我有一个字符串,我想从中提取 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'
>>>
如果我可以在没有[_0-9] 的情况下以某种方式匹配\w,但我不知道如何。即使我知道如何做到这一点,是否有像 [:alpha:] 这样的现成快捷方式可以在 Python 中使用?
【问题讨论】:
-
至于
[:alpha:],这只适用于字符类,所以正确的正则表达式应该是[[:alpha:]]+,但Python无论如何都不支持这些。 -
为什么不简单地在字符串上调用 .split()?
标签: python regex unicode character-properties