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
原创粉丝点击