利用正则表达式完成下面的操作:
一、不定项选择题
-
能够完全匹配字符串"(010)-62661617"和字符串"01062661617"的正则表达式包括(ABD)
A.
r"\(?\d{3}\)?-?\d{8}"
B.r"[0-9()-]+"
中括号里面的字符出现任意次
C.r"[0-9(-)]*\d*"
(-) 表示(到)的所有字符
D.r"[(]?\d*[)-]*\d*"
[(]就是一个(; [)-]是)- -
能够完全匹配字符串"back"和"back-end"的正则表达式包括( ABCD)
A.r'\w{4}-\w{3}|\w{4}'
B.r'\w{4}|\w{4}-\w{3}'
C.r'\S+-\S+|\S+'
大写的S — 非空白字符
D.r'\w*\b-\b\w*|\w*'
-
能够完全匹配字符串"go go"和"kitty kitty",但不能完全匹配“go kitty”的正则表达式包括(
BAD)
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"的正则表达式包括(BC)
A.r"a*?b"
B.r"a{,2}b"
C.r"aa??b"
??非贪婪(有一个或两个a)
D.r"aaa??b"
有两个或三个a
二、编程题
1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
from re import fullmatch
name = 'wrf92/_3'
result = fullmatch(r'[a-zA-Z_][\da-zA-Z_]{5,15}',name)
print(result)
- 密码匹配
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
pw = 'd232h32j4'
result = fullmatch(r'[a-zA-Z][^!@#¥%^&*]{5,11}',pw)
print(result)
- ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255
"""
判断字符串是否是0~255的数字
合法:0、1、11、199、249、255
不合法:256、00、001、012、098
0-9: \d
10-99: [1-9]\d
100-199: 1\d\d
200-249: 2[0-4]\d
250-255: 25[0-5]
0~255的数字的正则:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]
ip正则:((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])
"""
ip = '10.7.169.255'
result = fullmatch(r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])', ip)
print(result)
- 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
str1 = '-3.14good0087nice19b6ye23.'
result = findall(r'-?\d+\.?\d*', str1)
print(sum([float(x) for x in result]))
-
验证输入内容只能是汉字
str1 = '啦啦啦' result = fullmatch(r'[\u4e00-\u9fa5]+',str1) print(result)
-
匹配整数或者小数(包括正数和负数)
# 整数正则:[+-]?([1-9]\d*|0) # 小数数正则:[+-]?([1-9]\d*|0)\.\d+ # 合法数字:[+-]?([1-9]\d*|0)(\.\d+)? str1 = '-23.34' result = fullmatch(r'-?[1-9]+.?[0-9]+',str1) print(result)
-
验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0user_name = 'fdsa312_3e2' qq_num = '2323424' name = fullmatch(r'[a-zA-Z_0-9]{6,20}',user_name) qq = fullmatch(r'[1-9][0-9]{4,11}',qq_num) print(name,qq)
-
拆分长字符串:将一首诗的中的每一句话分别取出来
poem = ‘窗前明月光,疑是地上霜。举头望明月,低头思故乡。’
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
result = split(r'[,。]', poem)
print(result)