# Python编程快速上手 7.2正则匹配电话号码(随书练习)
1.匹配
str = 'my number is 415-55-4242.'
phoneNumberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # 匹配规则
mo = phoneNumberRegex.search(str)
print('phone number found:'+mo.group())
故障:
AttributeError: 'NoneType' object has no attribute 'group'
故障原因:
Regex 对象的 .search(),方法如果字符串中没有扎到该表达模式,那么search()方法将返回None,如果找到将返回一个Match对象,Match有一个group()方法,它返回被查找字符中实际被匹配的文本,本段程序中未匹配到符合要求的字符串,因此返回None,没有Match对象,调用group()方法出现报错
解决方式:
str = 'my number is 415-55-4242.'
phoneNumberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # 匹配规则
mo = phoneNumberRegex.search(str)
print('phone number found:'+mo.group())
if mo:
print('phone number found:' + mo.group())
else:
print('未匹配到符合要求的字符串')
怎么加一个判断,有Match对象再去调用group()方法
2.表达式问题
re.error: missing ), unterminated subpattern at position 0
phoneNumberRegex_2 = re.compile(r'(\d\d\d-(\d\d\d)-(\d\d\d\d)') # 错误表达式,第一个分组时缺少括号
phoneNumberRegex_2 = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # 正确表达式