import re
print(re.match('www', 'www.runoob.com').span())
print(re.match('www', 'www.runoob.com'))
print(re.match('com', 'www.runoob.com'))
print(re.search('www', 'www.runoob.com').span())
print(re.search('www', 'www.runoob.com'))
print(re.search('com', 'www.runoob.com'))
print(re.search('com', 'www.runoob.com').span())
输出结果
(0, 3)
<_sre.SRE_Match object; span=(0, 3), match='www'>
None
(0, 3)
<_sre.SRE_Match object; span=(0, 3), match='www'>
<_sre.SRE_Match object; span=(11, 14), match='com'>
(11, 14)
//检索和替换
phone = "2004-959-559 # 这是一个国外电话号码"
num = re.sub(r'#.*$', "", phone)
print "电话号码是: ", num
num = re.sub(r'\D', "", phone)
print "电话号码是 : ", num
输出结果
电话号码是: 2004-959-559
电话号码是 : 2004959559