本篇内容介绍了“python中re.findall函数的实例用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
1、findall函数返回字符串中所有匹配结果的正则表达式列表。
2、如果没有分组的正则是返回的正则匹配,分组返回的是分组匹配而非整个正则匹配。
找到所有与pattern匹配的子串(不重叠),并将其放入列表。
import re
lst = re.findall("[1-9]\d*","qw21313h2o58p4kjh8123jkh8435u")
for x in lst:
print(x,end=" ")
#输出结果:21313 1 58 4 8123 8435
实例扩展:
python3中函数说明:
findall(pattern, string, flags=0)
Return a list of all non-overlapping matches in the string.
If one or more capturing groups are present in the pattern, return
a list of groups; this will be a list of tuples if the pattern
has more than one group.
Empty matches are included in the result.
两种形式的使用方法:
import re
kk = re.compile(r'\d+')
kk.findall('one1two2three3four4')
#[1,2,3,4]
#注意此处findall()的用法,可传两个参数;
kk = re.compile(r'\d+')
re.findall(kk,"one123")
#[1,2,3]
其中,含()时要注意:
import re
string="abcdefg acbdgef abcdgfe cadbgfe"
#带括号与不带括号的区别
#不带括号
regex=re.compile("((\w+)\s+\w+)")
print(regex.findall(string))
#输出:[('abcdefg acbdgef', 'abcdefg'), ('abcdgfe cadbgfe', 'abcdgfe')]
regex1=re.compile("(\w+)\s+\w+")
print(regex1.findall(string))
#输出:['abcdefg', 'abcdgfe']
regex2=re.compile("\w+\s+\w+")
print(regex2.findall(string))
#输出:['abcdefg acbdgef', 'abcdgfe cadbgfe']
“python中re.findall函数的实例用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。