匹配任何 Unicode 字母? [英] Match any unicode letter?

查看:57
本文介绍了匹配任何 Unicode 字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .net 中你可以使用 \p{L} 来匹配任何字母,我如何在 Python 中做同样的事情?即,我想匹配任何大写、小写和重音字母.

解决方案

Python 的 re 模块尚不支持 Unicode 属性.但是您可以使用 re.UNICODE 标志编译您的正则表达式,然后字符类速记 \w 也将匹配 Unicode 字母.

由于 \w 也将匹配数字,因此您需要从字符类中减去这些数字以及下划线:

[^\W\d_]

将匹配任何 Unicode 字母.

<预><代码>>>>进口重新>>>r = re.compile(r'[^\W\d_]', re.U)>>>r.match('x')<_sre.SRE_Match 对象在 0x0000000001DBCF38>>>>r.match(u'é')<_sre.SRE_Match 对象在 0x0000000002253030>

In .net you can use \p{L} to match any letter, how can I do the same in Python? Namely, I want to match any uppercase, lowercase, and accented letters.

解决方案

Python's re module doesn't support Unicode properties yet. But you can compile your regex using the re.UNICODE flag, and then the character class shorthand \w will match Unicode letters, too.

Since \w will also match digits, you need to then subtract those from your character class, along with the underscore:

[^\W\d_]

will match any Unicode letter.

>>> 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>

这篇关于匹配任何 Unicode 字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆