书名: 《精通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'>