python网络爬虫学习(四)正则表达式的使用之re的其他方法

在上一篇文章中,我们学习了re的match方法,那么掌握了match方法,其他的方法学起来就相对轻松许多,下面对这些方法进行介绍

re.search

search方法与match方法最大的不同在于,match方法要求必须是从字符串的起始开始匹配,而search则会扫描整个字符串进行匹配。下面给出示例代码:

# -*-coding=utf-8 -*-
import re
pattern=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()

结果

1
2
3

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值