在 .net 中你可以\p{L}
用来匹配任何字母,我如何在 Python 中做同样的事情?即,我想匹配任何大写、小写和重音字母。
问问题
9503 次
2 回答
31
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>
于 2011-06-11T07:09:36.893 回答
7
PyPi 正则表达式模块支持\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 演示
于 2020-06-01T08:36:57.827 回答