本文來自於千鋒教育在阿里雲開發者社區學習中心上線課程《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)