try: '''Code where exceptions may occur''' except ValueError: ''''Print some tips or processing content''' except NameError: '''...''' except Exception: '''Universal exceptions cannot be used indiscriminately'''
try: '''Code where exceptions may occur''' except ValueError: ''''Print some tips or processing content''' except NameError: '''...''' except Exception: '''Universal exceptions cannot be used indiscriminately''' else: '''All the above except are not executed'''
try: '''Code where exceptions may occur''' except ValueError: '''Print some tips or processing content''' else: '''The code in the try is executed normally''' finally: '''Whether an error occurs or not, this code will be executed to do some beginning and end work'''
number = input('please input your phone number:') if number.isdigit() and number.startswith('13')\ or number.startswith('14')\ or number.startswith('15')\ or number.startswith('16')\ or number.startswith('17')\ or number.startswith('18')\ or number.startswith('19'): print('Pass check') else: print('Format error') The above code is too verbose, use regular number = input('please input your phone number:') ret = re.match('(13|14|15|16|17|18|19)[0-9]{9}',number) if ret:print('passed the initial check')
Example one:
Match the mobile phone number, you can use the regular.
with open('a',encoding='utf-8')as f1: li = [] for i in f1: i = i.strip() ret = re.findall('1[3-9]\d{9}',i) li.extend(ret) #extend merge print (li)
regular expression
Online testing tool http://tool.chinaz.com/regex/
Then we need to consider more about the range of characters that can appear in the same position.
Character group: [Character group]
Various characters that may appear in the same position form a character group. In regular expressions, use [] to indicate that the
characters are divided into many categories, such as numbers, letters, punctuation and so on.
If you now require a position "only one number can appear", then the character at this position can only be one of 10 numbers 0, 1, 2...9.
match uppercase
case match
. is omnipotent, except for newlines
match whitespace
focus
^
|
matches the beginning of the string
|
$
|
matches the end of the string
|
starts with the sea
Regular expression, cannot be written after
It can only appear at the beginning, not in the middle or at the back
In this case, it is the only ke that can be placed anywhere.
Indicates that it matches more than 11 digits and cannot be less than 11 digits.
Match 15 digits, more matches
Match 1 or more times
Highlights:
Quantifiers can only constrain one string
Constraints here [A-Z]
Constrain [0-9] and [AZ] simultaneously
up to 2 times
With red line, not important
Meta characters, should be used with quantifiers
Requirements for Two Constraints
bad writing
Match at least 15 times
It's more professional
2 underscores are escaping
the result is a