爬虫常用正则表达式-Re模块极速入门

查询re更多-----help(re)

.’:通配符,代表任意一个字符,除\n以外,一个点一个字符
ret=re.findall('m...e',"cat and mouse")
ret
['mouse']
*’:重复匹配,允许*之前的一个字符重复多次
ret=re.findall('ca*t',"caaaaat and mouse")
ret
['caaaaat']
?’:重复匹配,但是?之前的字符只能重复0次或一次
ret1=re.findall('ca?t',"cat and mouse")
ret1
['cat']
ret2=re.findall('ca?t',"caaaaat and mouse")
ret2  #匹配未成功
[]
+’:重复匹配,+之前的字符至少是1次,不能是0次
ret=re.findall('ca+t',"caaaaat and mouse")
ret 
['caaaaat']
{}’:重复匹配,括号内自定义匹配次数,可以是具体的值,也可以是区间
ret1=re.findall('ca{5}t',"caaaaat and mouse")
ret1
['caaaaat']
ret2=re.findall('ca{1,5}t',"caaat and mouse")
ret2
['caaat']
[]’:定义匹配的字符范围,[a-zA-Z0-9]表示相应位置的字符要匹配英文符和数字,’-'表示范围
ret=re.findall('[0-9]{1,5}',"12 cats 456 and 6 mice")
ret 
['12', '456', '6']
ret=re.findall('[0-9]{1}',"12 cats 456 and 6 mice")
ret 
['1', '2', '4', '5', '6', '6']
^’:必须从字符串起始的位置开始匹配,不考虑后续字符串中是否存在
ret=re.findall('^m...e',"cat and mouse")
ret
[]
ret=re.findall('^c.....d',"cat and mouse")
ret
['cat and']
ret=re.findall('^c.t',"cat and mouse")
ret
['cat']
$’:从字符串终止的位置开始匹配
ret=re.findall('a.......e$',"cat and mouse")
ret
['and mouse']
|’:两个模式进行或匹配
ret=re.findall('cat|mouse',"cat and mouse")
ret
['cat', 'mouse']
\’:转义字符,如果字符串中有特殊字符需要匹配,就需要进行转义,如:. * ? + $ ^ [] {} | \ -
ret=re.findall('\^c.t',"^cat and mouse")
ret
['^cat']
ret=re.findall('\[...\]',"^cat [and] mouse")
ret
['[and]']

实战案例

s='''<div class="index-module_topbarLogo_2IqfR"><a href="https://www.baidu.com"><img src="https://mbdp01.bdstatic.com/static/landing-pc/img/logo_top.79fdb8c2.png" alt="到百度首页" title="到百度首页"></a></div>'''
re.findall("https://[a-zA-Z0-9/\.\-]*",s)
['https://www.baidu.com',
 'https://mbdp01.bdstatic.com/static/landing-pc/img/logo']
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值