利用正则表达式完成下面的操作:
一、不定项选择题
-
能够完全匹配字符串"(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+'
D.r'\w*\b-\b\w*|\w*'
-
能够完全匹配字符串"go go"和"kitty kitty",但不能完全匹配“go kitty”的正则表达式包括( AD )
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"
D.r"aaa??b"
二、编程题
1.用户名匹配
要求: 1.用户名只能包含数字 字母 下划线
2.不能以数字开头
3.⻓度在 6 到 16 位范围内
username = ‘lsd’
方法1:
result = fullmatch(r'[a-zA-Z_][a-zA-Z\d_]{5,15}', username)
if result:
print(username, '合法')
else:
print(username, '不合法')
方法2
def is_username(user: str):
t = fullmatch(r'[a-zA-Z_][a-zA-Z\d_]{5,15}', username)
return bool(t)
print(is_username(username))
- 密码匹配
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
def is_password(pw: str):
t = fullmatch(r'[a-zA-Z][^!@#¥%^&*]{5,11}', pw)
return bool(t)
- ipv4 格式的 ip 地址匹配
提示: IP地址的范围是 0.0.0.0 - 255.255.255.255
def is_ip(ip: str):
t = 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)
return bool(t)
print(is_ip('10.23.34.56'))
- 提取用户输入数据中的数值 (数值包括正负数 还包括整数和小数在内) 并求和
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
from functools import reduce
str4 = '-3.14good87nice+19b.23ye0003she23.'
nums = findall(r'[-]?\d+\.?\d*', str4)
result = reduce(lambda i1, i2: i1 + float(i2), nums, 0)
print(result) # 151.86
- 验证输入内容只能是汉字
result = fullmatch(r'[\u4e00-\u9fa5]+', '实施交随声附k和付')
print(bool(result))
- 匹配整数或者小数(包括正数和负数)
def is_num(str1: str):
t = fullmatch(r'[+-]?(0|[1-9]\d*)(\.\d+)?', str1)
return bool(t)
print(is_num(‘+3.89’))
7. 验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0
def is_qq(qq: str):
t = fullmatch(r'[1-9]\d{4,11}', qq)
return bool(t)
- 拆分长字符串:将一首诗的中的每一句话分别取出来
poem = ‘窗前明月光,疑是地上霜。举头望明月,低头思故乡。’
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
result = split(r'[,。]', poem)
print(result[:-1])
result = findall(r'[\u4e00-\u9fa5]+', poem)
print(result)