正则表达式实战例子
1. 验证电子邮件地址
定义一个合理的电子邮件格式,并检查给定的字符串是否符合这个模式。
import redef is_valid_email(email):# 定义电子邮件格式的正则表达式pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'return bool(re.match(pattern, email))# 测试
emails = ["example@example.com", "invalid-email", "another.valid+email@example.co.uk"]
for email in emails:print(f"{email}: {is_valid_email(email)}")
2. 提取网页中的所有链接
使用正则表达式来查找HTML文档中所有的<a>
标签及其href
属性。
import rehtml_content = """
<a href="http://example.com/page1">Link 1</a>
<a href='http://example.com/page2'>Link 2</a>
<a href="javascript:void(0)">Invalid Link</a>
"""# 匹配带有href属性的a标签,并提取href值
link_pattern = re.compile(r'<a\s+(?:[^>]*?\s+)?href=[\'"]([^\'"]*)[\'"][^>]*>')
links = link_pattern.findall(html_content)print("Extracted Links:", links)
3. 电话号码格式化
电话号码都转换成XXX-XXX-XXXX
的形式。
import redef format_phone_number(phone):# 去除非数字字符,并确保长度正确cleaned = re.sub(r'\D', '', phone)if len(cleaned) == 10:return f"{cleaned[:3]}-{cleaned[3:6]}-{cleaned[6:]}"else:return Nonephones = ["(123) 456-7890", "123.456.7890", "1234567890", "123-456-7890"]
formatted_phones = [format_phone_number(p) for p in phones]
print(formatted_phones)
4. 替换敏感信息
掩盖或删除这些敏感信息。这里我们用正则表达式来识别并替换信用卡号。
import redef mask_credit_card(text):# 替换所有连续16位数字的序列(信用卡号)为"****-****-****-1234"masked_text = re.sub(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b','****-****-****-1234', text)return masked_textlog_entry = "Customer paid with card number 4111-1111-1111-1111."
masked_log = mask_credit_card(log_entry)
print(masked_log)
5. 解析日志文件
使用正则表达式来解析这些日志条目,提取出IP地址、时间戳和请求路径等信息。
import relog_line = '127.0.0.1 - - [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326'# 解析日志条目的正则表达式
log_pattern = re.compile(r'(\S+) (\S+) (\S+) \[(.*?)\] "(.*?)" (\d{3}) (\d+|-)')match = log_pattern.match(log_line)
if match:ip_address, _, _, timestamp, request, status_code, size = match.groups()print(f"IP Address: {ip_address}")print(f"Timestamp: {timestamp}")print(f"Request: {request}")print(f"Status Code: {status_code}")print(f"Size: {size}")