让我们说,我有一个处理例外的首选解决方案 但有时仍然会出现异常,我不得不使用第二种不太优选的解决方案 我使用如下代码,它可能看起来不酷。如果有更好的练习,请咨询。
try:
print(undefined_varible)
except NameError:
try:
print("1st attempt to handle NameError exception")
except NameError:
print("2nd attempt to handle NameError exception")
更新:
这是我的真实代码
import re
def find_phone(text):
try:
pattern = re.compile(r"(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?")
#search for a phone number
mo = pattern.search(text)
phone = mo.group()
print (phone)
except AttributeError:
try:
#don't want to use this pattern always because it's too wide and not perfect
pattern = re.compile(r"(?:\+?(\d{1,3}))?[-. (]*(\d{1,3})[-. )]*(\d{1,3})[-. ]*(\d{1,4})([-. ]*(\d{1,4}))?([-. ]*(\d{1,4}))?(?: *x(\d{1,4}))?")
mo = pattern.search(text)
phone = mo.group()
print (phone)
except AttributeError:
print("phone number has not been found")
find_phone("here is the weird formatted phone number: +33 6 29 37 24 57")
答案 0 :(得分:-1)
我认为这就是你想要的:
import re
def find_phone(text):
pattern_preference = [
r"(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?",
r"(?:\+?(\d{1,3}))?[-. (]*(\d{1,3})[-. )]*(\d{1,3})[-. ]*(\d{1,4})([-. ]*(\d{1,4}))?([-. ]*(\d{1,4}))?(?: *x(\d{1,4}))?"
]
for pattern in pattern_preference:
try:
pattern = re.compile(pattern)
#search for a phone number
mo = pattern.search(text)
phone = mo.group()
print(phone)
break
except AttributeError:
pass
else:
print("phone number has not been found")
find_phone("here is the weird formatted phone number: +33 6 29 37 24 57")