Python re正则匹配中文,其实非常简单,把中文的unicode字符串转换成utf-8格式就可以了,然后可以在re中随意调用。
unicode中中文的编码为/u4e00-/u9fa5,因此正则表达式u”[\u4e00-\u9fa5]+”可以表示一个或者多个中文字符。
>>>importre >>>s='中文:123456aa哈哈哈bbcc'.decode('utf8') >>>s u'\u4e2d\u6587\uff1a123456aa\u54c8\u54c8\u54c8bbcc' >>>prints 中文:123456aa哈哈哈bbcc >>>re.match(u"[\u4e00-\u9fa5]+",s) <_sre.SRE_Matchobjectat0xb77742c0> >>>pat='中文'.decode("utf8") >>>re.search(pat,s) <_sre.SRE_Matchobjectat0x16a16df0> >>>newpat='这里是中文内容'.decode("utf8") >>>news=re.sub(pat,newpat,s) >>>printnews 这里是中文内容:123456aa哈哈哈bbcc
python学习网,大量的免费python视频教程,欢迎在线学习!