天天看點

四組案例解析正規表達式 | 手把手教你入門Python之九十二

上一篇: 貪婪和⾮貪婪模式 | 手把手教你入門Python之九十一 下一篇: 網絡通信概念 | 手把手教你入門Python之九十三 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。

正規表達式案例練習

1、使用者名比對

使用者名隻能包含數字、字母和下劃線

不能以數字開頭

長度在6到16位範圍

username = input('請輸入使用者名:')
# x = re.match(r'^[a-zA-Z_][a-zA-Z0-9_]{5,15}$', username)
x = re.fullmatch(r'[a-zA-Z_][a-zA-Z0-9_]{5,15}', username)
if x is None:
     print('輸入的使用者名不符合規範')
else:
    print(x)           

2、密碼比對

不能包含 !@%^&*字元

必須以字母開頭

長度在6到12位

password = input('請輸入密碼:')
y = re.fullmatch(r'[a-zA-Z][^!@#$%^&*]{5,11}', password)
if y is None:
    print('密碼不符合規範')
else:
    print(y)           

3、已知有檔案test.txt裡面的内容如下:

1000phone hello python

mobiletrain 大資料

1000phone java

mobiletrain html5

mobiletrain 雲計算

查找檔案中以1000phone開頭的語句,并儲存在清單中

z = []
try:
    with open('test.txt', 'r', encoding='utf8') as file:
        content = file.read()  # 讀出所有的内容
        z = re.findall(r'1000phone.*', content)
        print(re.findall(r'^1000phone.*', content, re.M))

        # while True:
            # content = file.readline().strip('\n')
            # if not content:
            #     break
            # if re.match(r'^1000phone', content):
            #     z.append(content)
except FileNotFoundError:
    print('檔案打開失敗')

print(z)           

4、ipv4格式的ip位址比對

提示:ip位址範圍是 0.0.0.0 ~ 255.255.255.255

num = input('請輸入一個數字:')
#    0~9      10~99            100 ~ 199  200~209 210~219 220~229 230~239 240~249  250~255
# \d:一位數   [1-9]\d:兩位數   1\d{2}:1xx  2:00~255
x = re.fullmatch(r'((\d|[1-9]\d|1\d{2}|2([0-4]\d|5[0-5]))\.){3}(\d|[1-9]\d|1\d{2}|2([0-4]\d|5[0-5]))', num)
print(x)


x = re.finditer(r'-?(0|[1-9]\d*)(\.\d+)?', '-90good87ni0ce19bye')
x = re.finditer(r'-?(0|[1-9]\d*)(\.\d+)?', '-90good87ni0ce19bye')
for i in x:
    print(i.group())

# 非捕獲分組
x = re.findall(r'(?:-)?\d+(?:\.\d+)?', '-90good87ni0ce19bye')
print(x)           

配套視訊