正则表达式实战例子

正则表达式实战例子

1. 验证电子邮件地址

定义一个合理的电子邮件格式,并检查给定的字符串是否符合这个模式。

python 复制代码
import re

def 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属性。

python 复制代码
import re

html_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的形式。

python 复制代码
import re

def 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 None

phones = ["(123) 456-7890", "123.456.7890", "1234567890", "123-456-7890"]
formatted_phones = [format_phone_number(p) for p in phones]
print(formatted_phones)
4. 替换敏感信息

掩盖或删除这些敏感信息。这里我们用正则表达式来识别并替换信用卡号。

python 复制代码
import re

def 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_text

log_entry = "Customer paid with card number 4111-1111-1111-1111."
masked_log = mask_credit_card(log_entry)
print(masked_log)
5. 解析日志文件

使用正则表达式来解析这些日志条目,提取出IP地址、时间戳和请求路径等信息。

python 复制代码
import re

log_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}")
相关推荐
富贵儿99818 小时前
NL2SQL 实践手记 05:表结构之外,还有业务知识——给查询流程接上 RAG
数据库·sql·ai·自然语言处理·langchain
csdn_aspnet19 小时前
如何使用 Docker 设置 PostgreSQL
运维·数据库·docker·postgresql·容器
皮皮林55119 小时前
CTO说MySQL单表行数不要超过2000w,为啥?
mysql
倔强的石头_21 小时前
KES Studio 与 DMS 辅助开发管理实践:让接入过程可视化
数据库
富贵儿9981 天前
NL2SQL 实践手记 06:四个角色怎样合作——拆解一个 Multi-Agent 查询系统
数据库·sql·ai·自然语言处理·langchain
codeejun1 天前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
Decay__1 天前
PostgreSQL 监控体系构建 —— postgres_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·postgresql
码农张31 天前
MySQL 8.4.13 LTS 压缩版安装步骤 + 规范配置文件
mysql
Decay__1 天前
PostgreSQL 告警与自动化运维 —— 告警分级收敛、Webhook、定时巡检、脚本库
运维·数据库·sql·postgresql
老纪的技术唠嗑局1 天前
OceanBase × 知跃空间智能:从感知,到记忆,再到行为,打造具身智能数据底座
数据库