Python Regex库的使用(2)

这里有两个Regex库的使用方法,一个是编译表达式,一个是多重匹配,其中后面那个值得注意。

#!/usr/bin/python
#coding=gbk

import re

regexes=[re.compile(p)
        for p in ['this','that']
        ]
text='Does this the match?'

print 'Text: %r\n' % text

for regex in regexes:
    print 'seeking "%s" ->' % regex.pattern, # pattern 是编译好的正则表达式

    if regex.search(text):
        print 'match'
    else:
        print 'No match'

text2='abcabcabcabcbdwaejdif abc'
print text2
#findall 是返回所有匹配的字符串
for match in re.findall('abc',text2):
    print 'Found "%s"' % match
#递归的方法把值和位置打印出来(全部找出来)
for match in re.finditer('abc',text2):
    print 'Found %s at the %d and %d' % (text2[match.start():match.end()],match.start(),match.end())
原文地址:https://www.cnblogs.com/xiaoCon/p/2952181.html