03.查找文本模式
(0)要求:
假设你希望在字符串中查找电话号码。你知道模式:3个数字,1个短横线,3个数字,1个短横线,再是4个数字,即XXX-XXX-XXXX
(1)不用正则表达式来查找文本模式
def isPhoneNumber(text)
if len(text) != 12:
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4,7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8,12):
if not text[i].isdecimal():
return False
return True
print('415-555-4242 is a number:')
print(isPhoneNumber('415-555-4242'))
#在更长的字符串中寻找这种文本模式,用下面的代码来替代上面代码中最后4个print函数调用
#message = ‘Call me at 415-555-1011 tomorrow.415-555-4242 is my office.’
#for i in range(len(message)):
#chunk = message[i:i+12]
#if isPhoneNumber(chunk):
#print('Phone number found: '+chunk)
#print('Done')
(2)用正则表达式来查找文本模式
(2.1)创建正则表达式对象
python中所有正则表达式的函数都在re模块中
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
(2.2)匹配Regex对象
phoneHumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneHumRegex.search('My number is 415-555-4242')
print('Phone numer found: '+mo.group())
Regex对象的search()方法查找传入的字符串,寻找该正则表达式的所有匹配,如果字符串中没有找到该正则表达式模式,search()方法返回None,如果找到了该模式,search方法将返回一个Match对象,Match对象有一个group()方法,它返回被查找字符串中实际匹配的文本
变量名mo是一个通用的名称,用于Match对象