验证邮箱地址格式是否正确
import re
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
email = 'example@domain.com'
if re.match(pattern, email):
print('Valid email')
else:
print('Invalid email')
验证中国大陆手机号码格式
import re
pattern = r'^1[3-9]\d{9}$'
phone = '13812345678'
if re.match(pattern, phone):
print('Valid phone number')
else:
print('Invalid phone number')
匹配HTTP/HTTPS协议的URL地址
import re
pattern = r'^https?:\/\/[\w\-]+(\.[\w\-]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?$'
url = 'https://www.example.com/path?param=value'
if re.match(pattern, url):
print('Valid URL')
else:
print('Invalid URL')
从URL中提取域名部分
import re
pattern = r'https?:\/\/([\w\.-]+)'
url = 'https://www.example.com/path/page.html'
match = re.search(pattern, url)
if match:
domain = match.group(1)
print(f'Domain: {domain}')
else:
print('No domain found')
匹配标准日期格式 YYYY-MM-DD
import re
pattern = r'^\d{4}-\d{2}-\d{2}$'
date = '2024-03-15'
if re.match(pattern, date):
print('Valid date format')
else:
print('Invalid date format')
验证密码包含大小写字母、数字和特殊字符,长度8-20位
import re
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,20}$'
password = 'StrongPass123!'
if re.match(pattern, password):
print('Strong password')
else:
print('Weak password')
匹配正整数(不包括0)
import re
pattern = r'^[1-9]\d*$'
number = '123'
if re.match(pattern, number):
print('Valid positive integer')
else:
print('Invalid positive integer')
匹配指定扩展名的文件(jpg、png、gif)
import re
pattern = r'^.+\.(jpg|jpeg|png|gif)$'
filename = 'image.jpg'
if re.match(pattern, filename, re.IGNORECASE):
print('Valid image file')
else:
print('Invalid image file')
验证IPv4地址格式
import re
pattern = r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
ip = '192.168.1.1'
if re.match(pattern, ip):
print('Valid IPv4 address')
else:
print('Invalid IPv4 address')
验证中国大陆18位身份证号码格式
import re
pattern = r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$'
id_card = '110101199001011234'
if re.match(pattern, id_card):
print('Valid ID card number')
else:
print('Invalid ID card number')