能够完全匹配字符串"(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*'
注意:\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 = 'vewd3425w_v'
result = fullmatch(r'([a-zA-Z_])\w{5,15}', username)
print(result)
要求: 1.不能包含!@#¥%^&*这些特殊符号
2.必须以字母开头
3.⻓度在 6 到 12 位范围内
password = 'adbrt32rew'
result = fullmatch(r'([a-zA-Z])[^!@#$%^&*]{5,11}', password)
print(result)
ipaddress = '233.233.233.0'
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])', ipaddress)
print(result)
例如:“-3.14good87nice19bye” =====> -3.14 + 87 + 19 = 102.86
str1 = '-3.14good87nice19bye'
nums = findall(r'-?\d+\.?\d*', str1)
result = sum([float(x) for x in nums])
print(result)
验证输入内容只能是汉字
nums = '的水果北五环'
result = fullmatch(r'[\u4e00-\u9fa5]+', nums)
print(result)
匹配整数或者小数(包括正数和负数)
注意:
89、-23、+34、0、2.33、-2.33、9.000 - 合法
0001、233.、.344、0023.4 - 不合法
整数正则:[-+]?(0|[1-9]\d+)
小数正则:[-=]?(0|[1-9]\d*)\.\d+
数字正则:[-=]?(0|[1-9]\d*)(\.\d+)?
nums = '-0.353'
result = fullmatch(r'[-=]?(0|[1-9]\d*)(\.\d+)?', nums)
print(result)
验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0
username = 'cdneijw23__cde43t5'
qq = '2378435'
result1 = fullmatch(r'\w{6,20}', username)
result2 = fullmatch(r'[1-9]\d{4,11}', qq)
if result1 and result2:
print(f'{username}和{qq}有效')
拆分长字符串:将一首诗的中的每一句话分别取出来
poem = ‘窗前明月光,疑是地上霜。举头望明月,低头思故乡。’
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
result = split(r',|。', poem)
print(result)