《精通Python网络爬虫》笔记 - 查找和替换函数及提取网址电话邮件实例

书名: 《精通Python网络爬虫》

作者:韦玮

索引:ISBN978-7-111-56208-5

出版社:机械工业出版社

出版时间:2017年3月

第二篇  第5章 正则表达式与Cookie

p61-65

re.match(),从字符串的初始位置开始匹配, 相当于筛选结果:开头是xxx

re.search(),搜索整个字符串查找匹配,相当于筛选结果: 包含有xxx

re.compile(),全局匹配函数,对正则表达式/搜索条件进行预编译,并输出所有的匹配结果,例:

import re

string="hellomypythonhispythonourpythonend"

pattern=re.compile(".python.”) #预编译

result=pattern.findall(string)  #找出符合模式的所有结果

print(result)

执行结果是一个数组: ['ypythonh','spythono','rpythone']

疑问:如果 string="apythonpythons"呢? 执行结果会返回两个字符串还是一个?

 

re.sub(),替换,格式为re.sub(pattern,rep,string,max)。rep代表用来替换的字符串,max定义最多替换几次。例:

import re

string="hellomypythonhispythonourpythonend"

pattern="python"

result1=re.sub(pattern,"php",string)

result2=re.sub(pattern,"php",string,2)

print(result1)

print(result2)

输出结果:

hellomyphpisphpurphpnd

hellomyphpisphpurpythonend

实例1:提取后缀为.com或.cn的url网址

import re

pattern="[a-zA-Z]+://[^\s]*[.com|.cn]"

string="<a href='http://www.baidu.com'>百度首页</a>"

print[result]

返回结果:

<_sre.SRE_Match object; span=(9,29),match='http://www.baidu.com'>

实例2:匹配电话号码,仅按数字位数筛选

import re

pattern="\d{4}-\d{7}|\d{3}-\d{8}"   # 4位数字+"-"+7位数字或3位数字+"-"+8位数字

string='021-62728263653682265236"

result=re.search(pattren,string)

print(result)

返回结果:<_sre.SRE_Match object; span=(0,12),match='021-62728263'>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值