当前位置: 首页 > news >正文

正则表达式实战例子

正则表达式实战例子

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}")
http://www.lryc.cn/news/500666.html

相关文章:

  • Hadoop不同版本的区别
  • QtCreator UI界面 菜单栏无法输入中文
  • java switch及其新特性
  • E卷-货币单位换算(100分)
  • 什么是MMD Maximum Mean Discrepancy 最大均值差异?
  • 沐风老师3DMAX摄相机阵列插件使用方法
  • Java Web 开发学习中:过滤器与 Ajax 异步请求
  • 数据结构 (36)各种排序方法的综合比较
  • 使用vue搭建不需要打包的前端项目
  • 发布订阅者=>fiber=>虚拟dom
  • Python-计算机中的码制以及基础运算符(用于分析内存)
  • yum 离线软件安装
  • 【C语言】17. 数据在内存中的存储
  • 二叉树概述
  • 【开源免费】基于SpringBoot+Vue.JS图书进销存管理系统(JAVA毕业设计)
  • 惠普M126a连接共享打印机故障0x000006ba,系统不支持请求的命令,print spooler重复停止
  • Chainlit集成LlamaIndex实现一个通过用户聊天对话的酒店预定系统
  • 计算机网络之网络层超详细讲解
  • 代码随想录算法训练营day51|动态规划part13
  • ESP8266自制桌宠机器狗
  • 【力扣】409.最长回文串
  • git 拉取代码时报错 gitignore Please move or remove them before you merge.
  • 19,[极客大挑战 2019]PHP1
  • MQTT消息服务器mosquitto介绍及说明
  • uniapp结合movable-area与movable-view实现拖拽功能
  • 十九(GIT2)、token、黑马就业数据平台(页面访问控制(token)、首页统计数据、登录状态失效)、axios请求及响应拦截器、Git远程仓库
  • 文生图模型开源之光!ComfyUI - AuraFlow本地部署教程
  • spring boot之@Import注解的应用
  • 【记录】用JUnit 4的@Test注解时报错java.lang.NullPointerException的原因与解决方法
  • Spring Boot 自动化脚本-多线程批量压缩图片