---
title: "Python中正则表达式对中文的匹配问题"
author: "cuixuxucui"
date: "2016-05-30T17:42:27Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2016-05-30T17:42:27Z"
id: 2301949
url: "https://smartblack.iteye.com/blog/2301949"
---

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

今天在用[Python](http://lib.csdn.net/base/11 "Python知识库")匹配中文的时候出了问题，要么匹配不到，要么乱码，搜索了一下，成功完成，写了一小段测试代码如下：

 

 

**\[python]** [view plain](http://blog.csdn.net/freedomqx/article/details/6237654 "view plain") [copy](http://blog.csdn.net/freedomqx/article/details/6237654 "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编码