匹配任意 Unicode 字母?
- 2025-03-21 09:05:00
- admin 原创
- 42
问题描述:
在 .net 中,您可以使用p{L}
来匹配任何字母,如何在 Python 中执行相同操作?也就是说,我想匹配任何大写、小写和重音字母。
解决方案 1:
Python 的re
模块尚不支持 Unicode 属性。但您可以使用该re.UNICODE
标志编译正则表达式,然后字符类简写w
也将匹配 Unicode 字母。
由于w
也会匹配数字,因此您需要从字符类中减去这些数字以及下划线:
[^Wd_]
将匹配任何 Unicode 字母。
>>> import re
>>> r = re.compile(r'[^Wd_]', re.U)
>>> r.match('x')
<_sre.SRE_Match object at 0x0000000001DBCF38>
>>> r.match(u'é')
<_sre.SRE_Match object at 0x0000000002253030>
解决方案 2:
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 演示
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD