findall():查询字符串中某个正则表达式模式全部的非重复出现情况。
一、正常匹配
正则表达式不支持子组匹配
import re
s = 'This and that.'
p = re.compile(r'th\w+', re.I) # 不区分大小写
print p.findall(s)
======================================
['This', 'that']
======================================
findall( ) 函数类似于 search( ) 函数,但与 match( ) 和 search( ) 的不同之处在于,findall( )总是返回一个列表。
如果 findall( ) 没有找到匹配部分,就返回一个空列表,但如果匹配成功,列表将包含所有成功的匹配部分。
二、存在子组
正则表达式支持子组匹配
import re
s = 'This and that.'
p = re.compile(r'(th\w+)', re.I) # 不区分大小写
print "r'(th\w+)' result:", p.findall(s)
p = re.compile(r'(th(\w+))', re.I)
print "r'(th(\w+))' result:", p.findall(s)
p = re.compile(r'th(\w+)', re.I)
print "r'th(\w+)' result:".ljust(20), p.findall(s)
======================================
r'(th\w+)' result: ['This', 'that']
r'(th(\w+))' result: [('This', 'is'), ('that', 'at')]
r'th(\w+)' result: ['is', 'at']
======================================
1、r'(th\w+)'
与r'th\w+'
findall( )匹配到多个结果,并以字符串列表的形式返回;
正则表达式r'(th\w+)'
中多存在一个子组匹配,但结果与r'th\w+'
相同;
当表达式中存在子组时,匹配结果只返回子组匹配的结果;
当存在一个子组时,结果会以字符串列表的形式返回;
2、r'(th\w+)'
与 r'(th(\w+))'
正则表达式
r'(th(\w+))'
中多存在一个子组匹配;
当存在多个子组时,结果会以元组列表的形式返回,每个元组保存多个子组匹配结果;
3、r'th(\w+)'
与 r'th\w+'
当表达式中存在子组时,匹配结果只返回子组匹配的结果;
当存在一个子组时,结果会以字符串列表的形式返回;