匹配任意Unicode字母?

20 投票
2 回答
12494 浏览
提问于 2025-04-16 19:21

在.net中,你可以用\p{L}来匹配任何字母。那么在Python中,我该怎么做呢?也就是说,我想匹配所有的大写字母、小写字母和带重音的字母。

2 个回答

10

PyPi的regex模块支持\p{L}这个Unicode属性类,还有很多其他功能。你可以在文档中找到“Unicode字符属性,包括脚本和区块”的部分,完整列表可以查看http://www.unicode.org/Public/UNIDATA/PropList.txt。使用regex模块很方便,因为它在任何Python版本中都能提供一致的结果(要注意,Unicode标准在不断发展,支持的字母数量也在增加)。

你可以通过pip install regex(或者pip3 install regex)来安装这个库,然后使用它。

\p{L}        # To match any Unicode letter
\p{Lu}       # To match any uppercase Unicode letter
\p{Ll}       # To match any lowercase Unicode letter
\p{L}\p{M}*  # To match any Unicode letter and any amount of diacritics after it

下面是一些使用示例:

import regex
text = r'Abc-++-Абв. It’s “Łąć”!'
# Removing letters:
print( regex.sub(r'\p{L}+', '', text) ) # => -++-. ’ “”!
# Extracting letter chunks:
print( regex.findall(r'\p{L}+', text) ) # => ['Abc', 'Абв', 'It', 's', 'Łąć']
# Removing all but letters:
print( regex.sub(r'\P{L}+', '', text) ) # => AbcАбвItsŁąć
# Removing all letters but ASCII letters:
print( regex.sub(r'[^\P{L}a-zA-Z]+', '', text) ) # => Abc-++-. It’s “”!

你可以查看这个在线Python演示

34

Python的re模块目前还不支持Unicode属性。不过,你可以使用re.UNICODE这个标志来编译你的正则表达式,这样\w这个字符类的简写就可以匹配Unicode字母了。

因为\w也会匹配数字,所以你需要把数字和下划线从你的字符类中去掉:

[^\W\d_]

这样就可以匹配任何Unicode字母了。

>>> import re
>>> r = re.compile(r'[^\W\d_]', re.U)
>>> r.match('x')
<_sre.SRE_Match object at 0x0000000001DBCF38>
>>> r.match(u'é')
<_sre.SRE_Match object at 0x0000000002253030>

撰写回答