re.compile将正则表达式转换为模式对象,可以实现更有效率的匹配。
re.search 会在给定字符串中寻找第一个匹配给正则表式的子字符串。找到函数返回MatchObject(值为True),否则返回None(值为False) 。因为返回值的性质,所以该函数可以用在条件语句中:
if re.serch(pat, string):
print ‘found it !’
re.math 会在给定字符串的开头匹配正则表达式。因此,re.math(‘p’ , ‘python’)返回真,re.math(‘p’ , ‘www.python’) 则返回假。
re.split根据模式匹配项来分割字符串
str1='www.python.org,python.org,,wwwwwww.python.org,w.python.org,,,,wwww.python.org'
print re.split('[,]+',str1)
输出:[' www.python.org', 'python.org', 'wwwwwww.python.org', 'w.python.org', 'wwww.python.org']
re.findall 是以列表形式返回给定模式的所有匹配项。
re.sub:使用给定内容替换字符串
str1=' www.python.org,python.org,,wwwwwww.python.org,w.python.org,,,,wwww.python.org'
print re.sub('.org','imooc',str1)
输出:www.pythonimooc,pythonimooc,,wwwwwww.pythonimooc,w.pythonimooc,,,,wwww.pythonimooc
re.escape 函数:可以对字符串中所有可能被解释为正则运算符的字符进行转义的应用函数。
如果字符串很长且包含很多特殊字符,而你又不想输入一大堆反斜线,可以使用这个函数:
str1='www.python.org,python.org,,wwwwwww.python.org,w.python.org,,,,wwww.python.org'
print re.escape(str1)
输出:www\.python\.org\,python\.org\,\,wwwwwww\.python\.org\,w\.python\.org\,\,\,\,wwww\.python\.org
匹配对象和组
简单来说,组就是放置在圆括号里内的子模块,组的序号取决于它左侧的括号数。组0就是整个模块,所以在下面的模式中:
‘There (was a (wee) (cooper)) who (lived in Fyfe)’
包含组有:
0 There was a wee cooper who lived in Fyfe
1 was a wee cooper
2 wee
3 cooper
4 lived in Fyfe
import re
m= re.match(r'www\.(.*)\..{3}','www.imooc.com')
print m.group()
print m.group(0)
print m.group(1)
print m.start(1)
print m.end(1)
print m.span(1)
输出:
www.imooc.com
www.imooc.com
imooc
4
9
(4, 9)
group方法返回模式中与给定组匹配的字符串
start 方法返回给定组匹配项的开始索引
end方法返回给定组匹配项的结束索引加1
span以元组(start,end)的形式返回给组的开始和结束位置的索引
参考:http://www.cnblogs.com/fnng/archive/2013/05/20/3089816.html