---
title: "Python中正则表达式对中文的匹配问题"
author: "cwsot"
date: "2012-07-06T09:45:02Z"
tags: []
categories: ["Web前端"]
slug: "python"
draft: false
lastmod: "2012-07-06T09:45:02Z"
id: 1579154
url: "https://cwsot.iteye.com/blog/1579154"
---

今天在用python匹配中文的时候出了问题，要么匹配不到，要么乱码，搜索了一下，成功完成，写了一小段测试代码如下： import re source = "s2f程序员杂志一2d3程序员杂志二2d3程序员杂志三2d3程序员杂志四2d3" temp = source.decode('utf8') xx=u"(+)" pattern = re.compile(xx) results = pattern.findall(temp) for result in results : print result   其中source为非unicode编码，要先将其转为unicode编码的temp 
　　然后写正则表达式xx，其中u的前缀表示正则表达式也要为unicode编码，因为正则表达式要和被匹配的文本使用同样编码 
　　unicode中中文的编码为\u4e00-\u9fa5 
　　调用匹配后直接便可打印出正确文字，此时返回的结果也为unicode编码