Press "Enter" to skip to content

Python re正则匹配中文

Python re正则匹配中文,其实非常简单,把中文的unicode字符串转换成utf-8格式就可以了,然后可以在re中随意调用将输入的utf-8中文解密为unicode,然后交由python处理(2014.10.09感谢QQ85897930纠正)。

unicode中中文的编码为/u4e00-/u9fa5,因此正则表达式u”[\u4e00-\u9fa5]+”可以表示一个或者多个中文字符

>>> import re

>>> s='中文:123456aa哈哈哈bbcc'.decode('utf8')
>>> s
u'\u4e2d\u6587\uff1a123456aa\u54c8\u54c8\u54c8bbcc'
>>> print s
中文:123456aa哈哈哈bbcc

>>> re.match(u"[\u4e00-\u9fa5]+",s)
<_sre.SRE_Match object at 0xb77742c0>

>>> pat='中文'.decode("utf8")
>>> re.search(pat,s)
<_sre.SRE_Match object at 0x16a16df0>

>>> newpat='这里是中文内容'.decode("utf8")

>>> news=re.sub(pat,newpat,s)
>>> print news
这里是中文内容:123456aa哈哈哈bbcc

参考资料:
http://blog.csdn.net/freedomqx/article/details/6237654
https://www.evernote.com/shard/s229/sh/0490e5c6-020f-4edc-9b35-1a4dcf1bef2d/192c189e398edf9a8c8f7abce1ac940a

2 Comments

  1. Anonymous 2014-08-04

    好像应该是encode

  2. Anonymous 2017-08-03

    失败

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *