re.findall(pattern, text)(关键词:python/正则表达式/re)

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)。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值