python怎么用正则表达式提取中文?

Python015

python怎么用正则表达式提取中文?,第1张

1、字符串line='\ufeffD0002044\x01大数据\x01数据分析\x01技术\x01工具\x01应用\n'

想提取出其中的“大数据”,“数据分析”,“技术”,“工具”,“应用”这些中文,用了正则表达式:

>>> pat2='\x01(.*?)'

>>> rs=re.compile(pat2).findall(line)

>>> print(rs)

['', '', '', '', '']

显示的结果是空,请问如何才能正确的提出中文部分。

2、原文: 法规名称:'《中华人民共和国合同法》',Items:[{法条名称:'第五十二条'

匹配成: 《中华人民共和国合同法》第五十二条

(?<=法规名称:\').*?(\',Items:[{法条名称:\').*?(?=\') 请问这样匹配哪里错了?Python报sre_constants.error: unterminated character set at position 22

3、Python re正则匹配中文,其实非常简单,把中文的unicode字符串转换成utf-8格式就可以了,然后可以在re中随意调用

unicode中中文的编码为/u4e00-/u9fa5,因此正则表达式u”[\u4e00-\u9fa5]+”可以表示一个或者多个中文字符

>>>import re

>>>s='中文:123456aa哈哈哈bbcc'.decode('utf8')

>>>s

u'\u4e2d\u6587\uff1a123456aa\u54c8\u54c8\u54c8bbcc'

>>>print s

中文:123456aa哈哈哈bbcc 。

#python2使用如下即可:

# encoding: UTF-8 

import re 

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

 

def extract_number(input):

    match = re.search(u"[\u4e00-\u9fa5]+", input)

    return match.group()

if __name__ == "__main__":

    print extract_number(unicode("dss2第三季度建安大sdssd43fds",'utf8'))

    

    

    

#python3使用如下:

# encoding: UTF-8 

import re 

def extract_number(input):

    match = re.search("[\u4e00-\u9fa5]+", input)

    return match.group()

if __name__ == "__main__":

    print (extract_number("dss2第三季度建安大sdssd43fds"))