温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中re.findall()怎么使用

发布时间:2022-07-28 10:31:06 来源:亿速云 阅读:136 作者:iii 栏目:开发技术

本篇内容介绍了“Python中re.findall()怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

在python中,通过内嵌集成re模块,程序媛们可以直接调用来实现正则匹配。本文重点给大家介绍python中正则表达式 re.findall 用法

re.findall():函数返回包含所有匹配项的列表。返回string中所有与pattern相匹配的全部字串,返回形式为数组。

Python中re.findall()怎么使用

示例代码1:【打印所有的匹配项】

import re
 
s = "Long live the people's Republic of China"
ret = re.findall('h', s)
 
print(ret)

运行结果:

Python中re.findall()怎么使用

 示例代码2:【如果未找到匹配项,返回空列表】

import re
 
s = "Long live the people's Republic of China"
ret = re.findall('USA', s)
 
print(ret)

运行结果:

Python中re.findall()怎么使用

示例代码:

import re
 
s = "https://blog.csdn.net/weixin_44799217"
ret = re.findall(r"^http", s)
print(ret)
 
ret2 = re.findall(r"[t,b,s]", s)  # 匹配括号中的其中一个字符
print(ret2)
 
ret3 = re.findall(r"\d\d\d", s)
print(ret3)
 
ret4 = re.findall(r"\d", s)
print(ret4)
 
ret5 = re.findall(r"[^\d]", s)  # 取非
print(ret5)
 
ret6 = re.findall(r"[^https://]", s)  # 取非
print(ret6)

运行结果:

Python中re.findall()怎么使用

获取网站中的title:

import requests
import re
 
url = 'https://pz.wendu.com/'
 
response = requests.get(url)
data = response.text
# print(data)
res = re.findall(r'<title>(.*?)</title>', data)[0]
print(res)

运行效果: 

Python中re.findall()怎么使用

“Python中re.findall()怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI