python—正则表达式小例

Python爬虫中,正则表达式是必备技能。本文分享了一些实用的正则表达式代码示例,旨在帮助读者通过实践提升正则操作能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果要学会Python爬虫,那么正则表达式是不可或缺的技能。在下收集了一些关于正则表达式的代码,多多练习,多多学习

#match函数应用
import re
print(re.match("done|quit",'d!one!done'))
print(re.match("\dcom","www.4comrunoob.5com"))
#search函数应用
import re
print(re.search("done|quit",'d!one!done'))
print(re.search("\dcom","www.4comrunoob.5com"))
import re
result=re.search(r"(\w)(?!.*\1)","abc@cslg.edu.cn")
print(result)

#match对象使用,一般情况的子模式,例1
import re
m=re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
print(m.group(0))
print(m.group(1))
print(m.group(2))
print(m.group(1,2))
m=re.match(r"(\w+) \1", "Isaac Isaac, physicist")
print(m.group(0))

#match对象使用,一般情况的子模式,例2
import re
m=re.match(r"(\d+)\.(\d+)","24.556")
print(m.groups())
print(m.group(0),m.group(1),m.group(2))



#match对象使用,命名子模式,例1
import re
m=re.match(r"(?P<first_name>\w+)(?P<last_name>\w+)", "Isaac Newton, physicist")
print(m.groupdict())
print(m.group())
print(m.group("first_name"))
print(m.group("last_name"))
print(m.groups())
print(m.group(0),m.group(1),m.group(2))


#match对象使用,命名子模式,例2
m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
print(m.groupdict())



#findall函数,直接用re模块
import re
s="aabc abcd abbcd aacd"
print(re.findall("aa"
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值