python--pattern中的match、search方法

1.match

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

这个方法将从string的pos下标处起尝试匹配pattern。

注意:这个方法并不是完全匹配。

当pattern结束时若string还有剩余字符,仍然视为成功。想要完全匹配,可以在表达式末尾加上边界匹配符'$'。

# encoding: UTF-8
import re
 
# 将正则表达式编译成Pattern对象
pattern1 = re.compile(r'hello') #完全匹配
pattern2 = re.compile(r'hello%') #不完全匹配
 
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None
match1 = pattern1.match('hello world')
match2 = pattern2.match('hello world')
 
if match1:
    print match1.group()
else:
    print 'match1 failed'

if match2:
    print match2.group()
else:
    print 'match2 failed'
 
### 输出 ###
# hello
# match2 failed

2.search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
这个方法用于查找字符串中可以匹配成功的子串。

从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));

1.match()函数只检测re是不是在string的开始位置匹配,即只在position为0时开始;

2.search()会扫描整个string查找匹配

# -*- coding: utf-8 -*-
# 一个简单的search实例
import re
 
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'world')
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None
# 这个例子中使用match()无法成功匹配
match1 = pattern.search('hello world!')
match2 = pattern.match('hello world!')
 
if match1:
    # 使用Match获得分组信息
    print match1.group()
else:
    print 'failed 1'
if match2:
    print match2.group()
else:
    print 'failed 2'
 
### 输出 ###
# world
# failed 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值