由于中文使用2个字节来表示一个字,在正则表达式中如果不进行转换的话,编译器是不能识别的,所以这里简要谈一下正则表达式中遇到中文的问题。
关于python的re模块的基本用法,与各种正则表达式的基本形式,在之前的一篇文章中,进行过介绍,故此处不再赘述。
下面是一段对中文进行正则表达式处理的例子:使用Python3.3
import re
msg = "这是一个例子"
pat1 = "是"
pat2 = "是(..){1,2}" # 两个..表示一个中文字
pat3 = "是(..){1,2}?"
res1 = re.search(pat1.encode('gbk'), msg.encode('gbk')) # 匹配出'是'
if res1 is not None:
print(res1.group().decode('gbk'))
res2 = re.search(pat2.encode('gbk'), msg.encode('gbk')) # 匹配出'是一个'
if res2 is not None:
print(res2.group().decode('gbk'))
res3 = re.search(pat3.encode('gbk'), msg.encode('gbk')) # 匹配出'是一'
if res3 is not None:
print(res3.group().decode('gbk'))
res4 = re.search(pat1.encode('utf'), msg.encode('utf'))
if res4 is not None:
print(res4.group().decode('utf'))
res5 = re.search('t.'.encode('utf'), 'this'.encode('utf'))
if res5 is not None:
print(res5.group().decode('utf'))
中文一般是用‘gbk’进行编码。当使用‘utf’时只能处理确定的字,但不能模糊匹配,目前没弄清楚原因。