gpt4 book ai didi

python - 仅匹配 Python re 中的 unicode 字母

转载 作者:IT老高 更新时间:2023-10-28 22:20:57 27 4
gpt4 key购买 nike

我有一个字符串,我想从中提取 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 中使用?

最佳答案

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

[^\W\d_]

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

因此,它只允许 Unicode 字母。

关于python - 仅匹配 Python re 中的 unicode 字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8923949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com