day17-正则表达式作业
利用正则表达式完成下面的操作:
一、不定项选择题
-
能够完全匹配字符串"(010)-62661617"和字符串"01062661617"的正则表达式包括( A、B、D )
A.
r"\\(?\\d{3}\\)?-?\\d{8}"
B.r"[0-9()-]+"
C.r"[0-9(-)]*\\d*"
D.r"[(]?\\d*[)-]*\\d*"
-
能够完全匹配字符串"back"和"back-end"的正则表达式包括( A、B、C、D )
A.r'\\w{4}-\\w{3}|\\w{4}'
B.r'\\w{4}|\\w{4}-\\w{3}'
C.r'\\S+-\\S+|\\S+'
D.r'\\w*\\b-\\b\\w*|\\w*'
-
能够完全匹配字符串"go go"和"kitty kitty",但不能完全匹配“go kitty”的正则表达式包括(A、D)
A.r'\\b(\\w+)\\b\\s+\\1\\b'
B.r'\\w{2,5}\\s*\\1'
C.r'(\\S+) \\s+\\1'
D.r'(\\S{2,5})\\s{1,}\\1'
-
能够在字符串中匹配"aab",而不能匹配"aaab"和"aaaab"的正则表达式包括( B、C )
A.r"a*?b"
B.r"a{,2}b"
C.r"aa??b"
D.r"aaa??b"
二、编程题
1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
from re import fullmatch
account = input('请输入用户名:')
result = fullmatch(r'[a-z_A-Z][a-z\\d_A-Z]{5, 15}', account)
print(result)
- 密码匹配
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
from re import fullmatch
password = input('请输入密码:')
result = fullmatch(r'[a-zA-Z][^!@#¥%^&*]{5,11}', password)
print(result)
- ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255
from re import fullmatch
ip = input('请输入ip地址:')
result = fullmatch(r'((25[0-5]|1\\d{,2}|2[0-4]\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|1\\d{,2}|2[0-4]\\d|[1-9]\\d|\\d)', ip)
print(result)
- 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
from re import findall
result = findall(r'-?\\d+\\.\\d+|\\d+', '-3.14go2.od87ni6ce19bye')
print(sum([eval(x) for x in result]))
- 验证输入内容只能是汉字
from re import fullmatch
data = input('请输入:')
result = fullmatch(r'[\\u4e00-\\u9fa5]+', data)
print(result)
- 匹配整数或者小数(包括正数和负数)
from re import fullmatch
data = input('请输入:')
result = fullmatch(r'[+-]?[1-9]\\d*\\.?\\d*|[+-]?0\\.\\d*', data)
print(result)
- 验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0
from re import fullmatch
QQ = input('请输入QQ:')
account = input('请输入用户名:')
result1 = fullmatch(r'[a-z|\\d|_]*', account)
result2 = fullmatch(r'[1-9]\\d{4,11}', QQ)
print(result1, result2)
- 拆分长字符串:将一首诗的中的每一句话分别取出来
poem = ‘窗前明月光,疑是地上霜。举头望明月,低头思故乡。’
from re import split
data = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
result = split(r'[,。]', data)
result.pop()
print(result)