新闻动态

python中re.findall函数实例用法

发布日期:2022-02-01 10:09 | 文章来源:源码之家

1、findall函数返回字符串中所有匹配结果的正则表达式列表。

2、如果没有分组的正则是返回的正则匹配,分组返回的是分组匹配而非整个正则匹配。

实例

找到所有与pattern匹配的子串(不重叠),并将其放入列表。

import re
lst = re.findall("[1-9]\d*","qw21313h1o58p4kjh8123jkh8435u")
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函数实例用法的文章就介绍到这了,更多相关python中re.findall函数的介绍内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

美国稳定服务器

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部