在Python正则表达式中匹配Unicode字符
我看过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字符,比如øæå?我希望能在上面的标签组和文件名中都匹配到这些字符。
3 个回答
7
在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)
,./___,___-=+
(在后面的例子中,逗号是中文逗号。)
13
你需要使用 UNICODE 这个标志:
m = re.match(r'^/by_tag/(?P<tag>\w+)/(?P<filename>(\w|[.,!#%{}()@])+)$', '/by_tag/påske/øyfjell.jpg', re.UNICODE)
51
你需要指定 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的,而且也可以不需要 re.UNICODE
这个标志。