python中match的六种用法_Python中正则表达式match()、search()函数及match()和search()的区别详解...

match()和search()都是python中的正则匹配函数,那这两个函数有何区别呢?

match()函数只检测re是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none

例如:

#! /usr/bin/env python

# -*- coding=utf-8 -*-

import re

text = 'pythontab'

m = re.match(r"\w+", text)

if m:

print m.group(0)

else:

print 'not match'

结果是:pythontab

而:

#! /usr/bin/env python

# -*- coding=utf-8 -*-

#

import re

text = '@pythontab'

m = re.match(r"\w+", text)

if m:

print m.group(0)

else:

print 'not match'

结果是:not match

search()会扫描整个字符串并返回第一个成功的匹配

例如:

#! /usr/bin/env python

# -*- coding=utf-8 -*-

#

import re

text = 'pythontab'

m = re.search(r"\w+", text)

if m:

print m.group(0)

else:

print 'not match'

结果是:pythontab

那这样呢:

#! /usr/bin/env python

# -*- coding=utf-8 -*-

#

import re

text = '@pythontab'

m = re.search(r"\w+", text)

if m:

print m.group(0)

else:

print 'not match'

结果是:pythontab

总结:

python中正则表达式match()函数

如果不创建pattern对象,我们使用match函数可以直接进行正则表达式的匹配,在我看来这种方式更简洁,不过不适合大型程序的编写,后期维护可能会产生困难,不过编写一些小脚本完全可以胜任。

python中正则表达式search()函数

search函数和match函数有点类似,都可以匹配模式,但是match和search函数也有区别,而且区别很大,match函数只能够字符串的开始位置开始匹配,而search是可以匹配字符串的任意位置,但也是返回找到的第一个匹配的模式。我们通过例子来了解这俩之间的区别吧。

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值