search()查找字面量文本字符串的单个实例。findall(pattern, text)函数会返回输入中与模式匹配而不重叠的所有子串。
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print 'Found "%s"' % match
这个输入字符串中有两个ab实例。
Found "ab"
Found "ab"
第2个例子:
>>> import re
>>> match = re.findall(pattern, text)
>>> match
['ab', 'ab']
>>> import re
>>> text = 'abbaaabbbbaaaaa'
>>> pattern = 'ab'
>>> match = re.findall(pattern, text)
>>> match
['ab', 'ab']
第3个例子:
>>> import re
>>> formula = 'I + I = ME'
>>> re.findall('[A-Z]', formula)
['I', 'I', 'M', 'E']
第4个例子:
>>> import re
>>> formula = 'I + I = ME'
>>> re.findall('[A-Z]', formula)
['I', 'I', 'M', 'E']
>>> letters = ''.join(set(re.findall('[A-Z]', formula)))
>>> letters
'IEM'
第5个例子:
>>> import re
>>> formula = 'I + I == ME'
>>> words = re.findall('[A-Z]+', formula)
>>> words
['I', 'I', 'ME']
这里,[A-Z]+
是指至少1个大写字母。re.findall('[A-Z]+', formula)
意思是,找出formula
字符串中,所有的1、2、3……个大写字母的字符串,返回这些字符串的列表。
参考文献:
1. 《Python 标准库》 - 第1章 - 1.3 re 正则表达式 - 1.3.3 多重匹配(P11)。