# -*- coding:utf-8 -*- import re import sys reload(sys) sys.setdefaultencoding('utf-8') regexes = [re.compile(p) for p in ['this', 'that']] # 编译一个匹配模板对象列表,该列表匹配模板编译源来自一个二元列表 text = 'Does this text match the pattern?' print 'Test:', ' ', text for regex in regexes: # 查找每一个模板对象 print 'seeking "%s"-->' % regex.pattern, if regex.search(text): # search返回找到的第一个对象,没有找到则为空 print "match", regex.search(text).string else: print "no match", regex.search(text) print regex.findall(text) # findall返回找到所有匹配项组成的列表 # 正则表达式量词,转义字符,字符,锚钉码另见另章 # python3中匹配默认unicode.python2中默认ASCII。故匹配中文及特殊字符。Python2需特殊处理。 # 重新加载sys模块,指定默认utf-8。在目标字符串和模板前都加U即可。 source = u"s2f程序员杂志一2d3程序员杂志二2d3程序员杂志三2d3程序员杂志四2d3" xx = u"程序员" pattern = re.compile(xx) results = pattern.findall(source) print results[1]
python中RE正则匹配模块的用法若干
原创
©著作权归作者所有:来自51CTO博客作者magicpwn的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章