- 写一个正则表达式判断一个字符串是否是ip地址
规则:一个ip地址由4个数字组成,每个数字之间用.连接。每个数字的大小是0-255
255.189.10.37 正确
256.189.89.9 错误
re_str = r'(25[0-6]|2[0-4][0-9]|1\d\d|\d\d)\.(25[0-6]|2[0-4][0-9]|1\d\d|\d\d)\.(25[0-6]|2[0-4][0-9]|1\d\d|\d\d)\.(25[0-6]|2[0-4][0-9]|1\d\d|\d\d)'
#============================================
re_ip = 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])'
- 计算一个字符串中所有的数字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 结果是90+78+12.5 = 180.5
from re import *
str1 = 'hello90abc 78sjh12.5'
result = findall( r'\d+\.\d+|\d+',str1)
sum = 0
print(result)
for num in result:
sum += float(num)
print(sum)
#=======================================
re_num = r'[-+]?([1-9]\d*|0)(\.\d+)?'
nums = [x.group() for x in finditer(re_num, 'he+34,-323, -0.23llo90abc 78sjh12.5')]
sum1 = 0
for num in nums:
sum1 += float(num)
print(sum1)
#===========================================
re_num = r'-?\d+\.?\d*'
print(findall(re_num, 'he+34,-323, -0.23llo90abc 78sjh12.5'))
- 验证输入的内容只能是汉字
from re import *
while True:
str1 = input('请输入:')
re_str = r'[\u4e00-\u9fa5]+'
if not fullmatch(re_str, str1):
pass
else:
print(str1)
break
- 电话号码的验证
from re import *
while True:
str1 = input('请输入电话号码:')
re_str = r'1[3-9]\d{9}'
if not fullmatch(re_str, str1):
pass
else:
print(str1)
break
- 验证输入用户名和QQ号是否有效并给出对应的提示信息
要求:
用户名必须由字母、数字或下划线构成且长度在6~20个字符之间
QQ号是5~12的数字且首位不能为0
from re import *
while True:
str1 = input('请输入用户名:')
re_str = r'[a-zA-Z\d_]{6,20}'
if not fullmatch(re_str, str1):
print('用户名必须由字母、数字或下划线构成且长度在6~20个字符之间')
else:
print(str1)
while True:
str2 = input('请输入QQ号:')
re_str2 = r'[1-9]\d{4,11}'
if not fullmatch(re_str2, str2):
print('QQ号是5~12的数字且首位不能为0')
else:
print(str2)
break
break
-
拆分长字符串:将一首诗的中的每一句话分别取出来
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
from re import *
poem = '窗前明月光,疑是地上霜。举头望明月,低头思故乡。'
result = iter(split(r'[^\u4e00-\u9fa5]',poem))
for num in result:
print(num)
二、不定项选择题
- 能够完全匹配字符串“(010)-62661617”和字符串“01062661617”的正则表达式包括( B )
A. “(?\d{3})?-?\d{8}”
B. “[0-9()-]+”
C. “[0-9(-)]\d”
D. “[(]?\d[)-]\d*”
- 能够完全匹配字符串“c:\rapidminer\lib\plugs”的正则表达式包括(A,B,C )
A. “c:\rapidminer\lib\plugs”
B. “c:\rapidminer\lib\plugs”
C. “(?i)C:\RapidMiner\Lib\Plugs” ?i:将后面的内容的大写变成小写
D. “(?s)C:\RapidMiner\Lib\Plugs” ?s:单行匹配 - 能够完全匹配字符串“back”和“back-end”的正则表达式包括(A,B,C )
A. “\w{4}-\w{3}|\w{4}”
B. “\w{4}|\w{4}-\w{3}”
C. “\S+-\S+|\S+”
D. “\w\b-\b\w|\w*” - 能够完全匹配字符串“go go”和“kitty kitty”,但不能完全匹配“go kitty”的正则表达式包括( D)
A. “\b(\w+)\b\s+\1\b”
B. “\w{2,5}\s*\1”
C. “(\S+) \s+\1”
D. “(\S{2,5})\s{1,}\1” - 能够在字符串中匹配“aab”,而不能匹配“aaab”和“aaaab”的正则表达式包括(B,C )
A. “a*?b”
B. “a{,2}b”
C. “aa??b”
D. “aaa??b”