匹配python正则表达式中的unicode字符

Weh*_*olt 26 python regex unicode non-ascii-characters character-properties

我已经通过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'}
Run Code Online (Sandbox Code Playgroud)

一切都很好,然后我尝试用挪威字符(或更像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'
Run Code Online (Sandbox Code Playgroud)

如何匹配典型的unicode字符,例如øæå?我希望能够在上面的标签组和文件名的标签组中匹配这些字符.

Tho*_*mas 45

您需要指定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'}
Run Code Online (Sandbox Code Playgroud)

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


R. *_*des 12

你需要UNICODE标志:

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

  • 它也是Python3所必需的吗? (3认同)
  • @Kevin - 你不需要Python 3的unicode标志。“默认情况下,Python 3中已经为Unicode(str)模式启用了Unicode匹配......” - https://docs.python.org/3/howto /正则表达式.html (2认同)

184*_*615 6

在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)
,./___?___-=+
Run Code Online (Sandbox Code Playgroud)

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