1. 程式人生 > >Python正則表示式處理中文中的匹配

Python正則表示式處理中文中的匹配

由於中文使用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’時只能處理確定的字,但不能模糊匹配,目前沒弄清楚原因。