到目前为止,我们都是使用search方法来匹配单一的字符。使用findall方法可以匹配所有符合条件的字符,并返回一个对象集合。如下例所示:
1
2 3 4 5 6 |
__author__
=
'Administrator'
import re text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re. findall (pattern ,text ): print "Found %s" % match |
这个查询会返回两个符合条件的值,如下所示:
1
2 |
Found ab
Found ab |
除了findall还有一个方法finditer,这个方法返回的是匹配的Match对象集合,这样通过Match对象可以更灵活的操作返回结果,如下面的代码所示:
1
2 3 4 5 6 7 8 |
import
re
text = 'abbaaabbbbaaaaa' pattern = 'ab' for match in re. finditer (pattern ,text ): s =match. start ( ) e =match. end ( ) print "Found %s at %d,%d" % (text [s:e ] ,s ,e ) |
从上面的代码可以看出,我们可以通过返回的Match对象得到匹配对象所在的位置。其输出结果如下:
1
2 |
Found ab at 0,2
Found ab at 5,7 |