Python正则表达式中的匹配Unicode字符

2024-05-29 08:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经读过Stackoverflow上的其他问题,但仍然没有更进一步。很抱歉,如果我已经准备好了,但是我没有得到任何工作建议。

>>> import re
>>> m = re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', '/by_tag/xmas/xmas1.jpg')
>>> print m.groupdict()
{'tag': 'xmas', 'filename': 'xmas1.jpg'}

一切都很好,然后我尝试了一些挪威字符(或者更像unicode的字符):

>>> m = re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', '/by_tag/påske/øyfjell.jpg')
>>> print m.groupdict()
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groupdict'

如何匹配典型的unicode字符,如øå?我也希望能够在上面的标记组和filename的标记组中匹配这些字符。


Tags: 标记rebytagmatchunicodefilename字符
3条回答

您需要UNICODE标志:

m = re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', '/by_tag/påske/øyfjell.jpg', re.UNICODE)

您需要指定re.UNICODE标志,使用u前缀将字符串输入为Unicode字符串:

>>> re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', u'/by_tag/påske/øyfjell.jpg', re.UNICODE).groupdict()
{'tag': u'p\xe5ske', 'filename': u'\xf8yfjell.jpg'}

这是在Python 2中;在Python 3中,必须省略u,因为所有字符串都是Unicode。

在Python 2中,需要re.UNICODE标志和unicode字符串构造函数

>>> re.sub(r"[\w]+","___",unicode(",./hello-=+","utf-8"),flags=re.UNICODE)
u',./___-=+'
>>> re.sub(r"[\w]+","___",unicode(",./cześć-=+","utf-8"),flags=re.UNICODE)
u',./___-=+'
>>> re.sub(r"[\w]+","___",unicode(",./привет-=+","utf-8"),flags=re.UNICODE)
u',./___-=+'
>>> re.sub(r"[\w]+","___",unicode(",./你好-=+","utf-8"),flags=re.UNICODE)
u',./___-=+'
>>> re.sub(r"[\w]+","___",unicode(",./你好,世界-=+","utf-8"),flags=re.UNICODE)
u',./___\uff0c___-=+'
>>> print re.sub(r"[\w]+","___",unicode(",./你好,世界-=+","utf-8"),flags=re.UNICODE)
,./___,___-=+

(在后一种情况下,逗号是中文逗号。)

相关问题 更多 >

    热门问题