python中re模块的安装_python库之re模块

首先:re库中有

__all__ = [ "match", "search", "sub", "subn", "split", "findall",

"compile", "purge", "template", "escape", "I", "L", "M", "S", "X",

"U", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE",

"UNICODE", "error" ]

1.match:

这个函数的意思是从头开始匹配,如果有将匹配上的数据返回,但只返回第一个,如果没有匹配上将返回None,注意,这个函数的弊端就是如果你要找的数据在中间的某个部分,它是不会返回值的,返回None。

pattern = re.compile('\d+')

str = 'bbb1234aaa5678'

m = pattern.match(str)

m=

None

2.search:

为了解决上面的弊端,就出现了这个函数,这个函数可以从任何位置开始匹配,如果匹配上返回第一个数值,否则返回None。

pattern = re.compile('\d+')

str = 'bbb1234aaa5678'

n = pattern.search(str)

print n.group()

# n=

# 1234

3.sub

这个方法是被称作"替换"就是将你要替换的字段用其它的字段进行替换。pattern为匹配规则,strs使我们要进行替换的字符串,m中的hello word 是我们用它去替换我们匹配的东西。

pattern = re.compile('(\w+) (\w+)')

strs = 'hello 123, hello 456'

m = pattern.sub('hello word', strs)

print m

# hello word, hello word

4.subn

该函数返回的是一个数组,第一个参数是字符串,第二个参数是匹配成功的个数。

pattern = re.compile('(\w+) (\w+)')

strs1 = 'hello 123, hello 456'

m1 = pattern.subn('hello word', strs1)

匹配成功输出为:('hello word, hello word', 2)

strs2 = 'xxxxxxxxxxxxxx'

m2 = pattern.subn('hello word', strs2)

匹配失败输出为:('xxxxxxxxxxxxxx', 0)

5.split

根据模式的出现分割源字符串,返回包含结果子字符串的列表

pattern = re.compile('[\s\d\\\;]+')

m = pattern.split(r"a bb\aa;mm; a")

# ['a', 'bb', 'aa', 'mm', 'a']

6.findall

匹配全部符合规则的字符串。

pattern = re.compile('\d+')

m = pattern.findall('12a3d4f5g678s9d0dawsasda')

# ['12', '3', '4', '5', '678', '9', '0']

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值