Python中正则表达式对中文的匹配问题

http://blog.csdn.net/freedomqx/article/details/6237654

今天在用Python匹配中文的时候出了问题,要么匹配不到,要么乱码,搜索了一下,成功完成,写了一小段测试代码如下:

 

 

[python]  view plain  copy
 
  1. import re  
  2. source = "s2f程序员杂志一2d3程序员杂志二2d3程序员杂志三2d3程序员杂志四2d3"  
  3. temp = source.decode('utf8')  
  4. xx=u"([/u4e00-/u9fa5]+)"  
  5. pattern = re.compile(xx)  
  6. results =  pattern.findall(temp)  
  7. for result in results :  
  8.   print result  

其中source为非unicode编码,要先将其转为unicode编码的temp

然后写正则表达式xx,其中u的前缀表示正则表达式也要为unicode编码,因为正则表达式要和被匹配的文本使用同样编码

unicode中中文的编码为/u4e00-/u9fa5

调用匹配后直接便可打印出正确文字,此时返回的结果也为unicode编码

猜你喜欢

转载自smartblack.iteye.com/blog/2301949