python网络爬虫学习(四)正则表达式的使用之re的其他方法
来源:互联网 发布:怎么申请多个淘宝号 编辑:程序博客网 时间:2024/04/29 11:27
在上一篇文章中,我们学习了re的match方法,那么掌握了match方法,其他的方法学起来就相对轻松许多,下面对这些方法进行介绍
re.search
search方法与match方法最大的不同在于,match方法要求必须是从字符串的起始开始匹配,而search则会扫描整个字符串进行匹配。下面给出示例代码:
# -*-coding=utf-8 -*-import repattern=re.compile(r'world')match=re.search(pattern,r'hello world')if match: print match.group()else: print '匹配失败'
运行结果
world
re.split
split方法是按能够匹配的字符串将string分割,以列表形式返回
pattern3=re.compile(r'\d+')//匹配到数字,分割match3=re.findall(pattern3,r'one1two2three2four')print match3
结果
['one', 'two', 'three', 'four']
re.findall
搜索string,以列表返回所有匹配的字符串
pattern3=re.compile(r'\d+')match3=re.findall(pattern3,r'one1two2three2four')print match3
结果
['1', '2', '3']
re.finditer
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器
for match4 in re.finditer(pattern4,r'one1two2three3four'): print match4.group()
结果
123
re.sub(pattern, repl, string[, count])
sub方法使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g、\g引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换,代码示例:
s=r'i say,hello world'pattern=re.compile(r'(\w+) (\w+)')match=re.sub(pattern,r'\2 \1',s)print match
运行结果
say i,world hello
re.subn
返回sub替换的次数
count=re.subn(pattern,r'\2 \1',s)print count
运行结果
('say i,world hello', 2)
如果只需要次数,代码如下:
count=re.subn(pattern,r'\2 \1',s)print count[1]
0 0
- python网络爬虫学习(四)正则表达式的使用之re的其他方法
- python网络爬虫学习(三)正则表达式的使用之re.match方法
- python爬虫之re正则表达式库
- Python 之 【re模块的正则表达式学习】
- Python的re模块学习---正则表达式
- python - re (正则表达式的学习)
- PYTHON RE模块 正则表达式的使用
- Python爬虫实践(七):正则表达式(2) re模块的使用
- python爬虫由浅入深8---正则表达式及Re库的基础与使用
- 在学习python网络爬虫时用到的正则表达式
- python的正则表达式 re
- python的re正则表达式
- python的正则表达式 re
- python的正则表达式 re
- 正则表达式的方法--re
- python学习之2 正则表达式re
- Python基础学习之re正则表达式
- python网络爬虫学习笔记之之正则表达式
- java反射——基础
- Activity的跳转
- jsp中文乱码
- java中读取properties文件
- SVM笔记(四) 线性支持向量机
- python网络爬虫学习(四)正则表达式的使用之re的其他方法
- 153_getView方法的抽取
- iOS开发--遇到的友盟的几个坑
- HMM模型在中文分词中的应用
- kobject
- 计蒜客之矩阵翻转
- 网页性能优化
- 代码训练营——进制转换
- 计数方式比较