- 寫一個正則表達式判斷一個字符串是否是ip地址
規(guī)則:一個ip地址由4個數(shù)字組成田篇,每個數(shù)字之間用.連接礁鲁。每個數(shù)字的大小是0-255
255.189.10.37 正確
256.189.89.9 錯誤
from re import *
re_ip = r'(\d\.|\d\d\.|[0-2]\d\d\.){3}(\d|\d\d|[0-2]\d\d)'
result = fullmatch(re_ip, '12.144.1.251')
print(result) # <re.Match object; span=(0, 12), match='12.144.1.251'>
- 計算一個字符串中所有的數(shù)字的和
例如:字符串是:‘hello90abc 78sjh12.5’ 結(jié)果是90+78+12.5 = 180.5
from re import *
str1 = 'hello90abc 78sjh12.5j'
result = findall(r'\d+\.\d|\d+', str1)
y = 0
for x in result:
y += float(x)
print(y) # 180.5
- 驗證輸入的內(nèi)容只能是漢字
from re import *
str1 = input('請輸入:')
result = fullmatch(r'[\u4e00-\u9fa5]', str1)
if result:
print('輸入正確!')
else:
print('輸入錯誤螟炫!')
- 電話號碼的驗證
from re import *
str1 = input('請輸入:')
result = fullmatch(r'1[3-9][0-9]{9}', str1)
if result:
print('輸入的為手機號碼波附!')
else:
print('輸入的非手機號碼!')
- 驗證輸入用戶名和QQ號是否有效并給出對應(yīng)的提示信息
要求:
用戶名必須由字母昼钻、數(shù)字或下劃線構(gòu)成且長度在6~20個字符之間
QQ號是5~12的數(shù)字且首位不能為0
from re import *
qq = input('請輸入QQ賬號:')
key = input('請輸入密碼:')
result = fullmatch(r'[1-9][0-9]{4,11}', qq)
if result:
result1 = fullmatch(r'[a-zA-Z\d_]{6,20}', key)
if result1:
print('密碼格式正確掸屡!')
else:
print('密碼格式錯誤!')
else:
print('QQ號碼格式有誤然评!')
- 拆分長字符串:將一首詩的中的每一句話分別取出來
from re import *
poem = '床前明月光仅财,疑是地上霜。舉頭望明月碗淌,低頭思故鄉(xiāng)盏求。'
result = split(r'抖锥,|。', poem)
for x in result:
print(x)
# 床前明月光
# 疑是地上霜
# 舉頭望明月
# 低頭思故鄉(xiāng)
二碎罚、不定項選擇題
- 能夠完全匹配字符串“(010)-62661617”和字符串“01062661617”的正則表達式包括( B )
A. “(?\d{3})?-?\d{8}”
B. “[0-9()-]+”
C. “[0-9(-)]\d”
D. “[(]?\d[)-]\d*”
- 能夠完全匹配字符串“c:\rapidminer\lib\plugs”的正則表達式包括( )
A. “c:\rapidminer\lib\plugs”
B. “c:\rapidminer\lib\plugs”
C. “(?i)C:\RapidMiner\Lib\Plugs” ?i:將后面的內(nèi)容的大寫變成小寫
D. “(?s)C:\RapidMiner\Lib\Plugs” ?s:單行匹配 - 能夠完全匹配字符串“back”和“back-end”的正則表達式包括( ABC )
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”的正則表達式包括( AD )
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”的正則表達式包括( BC )
A. “a*?b”
B. “a{,2}b”
C. “aa??b”
D. “aaa??b”