Assignment: Use regular expressions to complete the following operations
1. Username matching
Requirements:
a. The user name can only contain alphanumeric underscores
b. Cannot start with a number
c. Length is in the range of 6 to 16 bits
from re import fullmatch
user=input('请输入用户名:')
user_name=r'[a-zA-Z_][a-zA-Z_\d]{5,15}'
print(fullmatch(user_name,user))
- Password match
Requirements: 1. Cannot include these special symbols @#¥%^&*
2. Must start with a letter
3. Length is in the range of 6 to 12 digits
from re import fullmatch
password=input('请输入用户名:')
user_password=r'[a-zA-Z][^!@#¥%^&*]{5,11}'
print(fullmatch(user_password,password))
- IP address matching in ipv4 format
Tip: The range of IP address is 0.0.0.0-255.255.255.255
user=input('请输入ip地址:')
user_name=r'([1-9]?\d\.){3}\d|(1\d\d\.){3}1\d\d|(2[0-4]\d\.){3}2[0-4]\d|(25[0-5]\.){3}25[0-5]'
print(fullmatch(user_name,user))
- Extract the value in the user input data (the value includes positive and negative numbers as well as integers and decimals) and sum
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
from re import findall
from functools import reduce
str1='-3.14go-.od87nice19bye'
str2=r'-?\d+\.?\d*'
result=findall(str2,str1)
print(reduce(lambda x,y :x+float(y),result,0))
-
Verify that the input content can only be Chinese characters
from re import fullmatch strs=input('请输入中文:') print(fullmatch(r'[\u4e00-\u9fa5]+',strs))
-
Match integers or decimals (including positive and negative numbers)
from re import fullmatch strs=input('请输入一个数:') print(fullmatch(r'[+-]?(0|[1-9]\d*|0\.\d+|[1-9]\d*\.\d+)',strs))
-
Gets a string using a regular expression in all date information to match date date format: 2018-12-6
Note that the range of year is 1~9999, the range of month is 1~12, and the range of day is 1 30 or 1 31 or 1~29 (leap years are not considered)
from re import fullmatch str1=r'[1-9]\d{3}-([13578]|1[0-2])-(\d|[1-2]\d|3[01])' str2=r'[1-9]\d{3}-([469]|11)-([1-9]|[1-2]\d|30)' str3=r'[1-9]\d{3}-2-([1-9]|[1-2]\d)' def strs(*args): for i in args: str4=fullmatch(i,'2018-12-6') if str4 !='None': return str4 result=strs(str1,str2,str3) print(result)