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