简体   繁体   English

带有Unicode字符的Python正则表达式错误?

[英]Python regex with unicode characters bug?

Long story short: 长话短说:

>>> re.compile(r"\w*").match(u"Français")
<_sre.SRE_Match object at 0x1004246b0>
>>> re.compile(r"^\w*$").match(u"Français")
>>> re.compile(r"^\w*$").match(u"Franais")
<_sre.SRE_Match object at 0x100424780>
>>> 

Why doesn't it match the string with unicode characters with ^ and $ in the regex? 为什么正则表达式中的Unicode和^$不匹配? As far as I understand ^ stands for the beginning of the string(line) and $ - for the end of it. 据我了解, ^代表字符串(行)的开头, $代表字符串的结尾。

You need to specify the UNICODE flag , otherwise \\w is just equivalent to [a-zA-Z0-9_] , which does not include the character ' ç '. 您需要指定UNICODE标志 ,否则\\w等效于[a-zA-Z0-9_] ,其中不包含字符' ç '。

>>> re.compile(r"^\w*$", re.U).match(u"Fran\xe7ais")
<_sre.SRE_Match object at 0x101474168>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM