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

08_正则表达式

第8课:正则表达式

课程目标

  • 理解正则表达式的基本概念
  • 掌握常用的正则表达式模式
  • 学习Python中re模块的使用
  • 能够编写简单的正则表达式

1. 正则表达式基础

1.1 什么是正则表达式

正则表达式是一种用于匹配字符串模式的工具,可以用于搜索、替换和验证文本。

1.2 基本语法

import re# 基本匹配
text = "Hello, World!"
pattern = r"Hello"
match = re.search(pattern, text)
if match:print("找到匹配:", match.group())

2. 常用模式

2.1 字符类

import retext = "The cat sat on the mat."# 匹配单个字符
pattern = r"cat"
matches = re.findall(pattern, text)
print("匹配结果:", matches)  # ['cat']# 字符类 [abc] 匹配a、b或c中的任意一个
pattern = r"[cat]"
matches = re.findall(pattern, text)
print("字符类匹配:", matches)# 范围字符类 [a-z] 匹配小写字母
pattern = r"[a-z]+"
matches = re.findall(pattern, text)
print("小写字母匹配:", matches)# 否定字符类 [^abc] 匹配除了a、b、c之外的字符
pattern = r"[^aeiou\s]+"
matches = re.findall(pattern, text)
print("非元音字母匹配:", matches)

2.2 量词

import retext = "aaabbbcccddd"# * 匹配0个或多个
pattern = r"a*"
matches = re.findall(pattern, text)
print("a*匹配:", matches)# + 匹配1个或多个
pattern = r"a+"
matches = re.findall(pattern, text)
print("a+匹配:", matches)# ? 匹配0个或1个
pattern = r"a?"
matches = re.findall(pattern, text)
print("a?匹配:", matches)# {n} 匹配恰好n个
pattern = r"a{3}"
matches = re.findall(pattern, text)
print("a{3}匹配:", matches)# {n,m} 匹配n到m个
pattern = r"a{2,4}"
matches = re.findall(pattern, text)
print("a{2,4}匹配:", matches)

2.3 特殊字符

import retext = "Hello\nWorld\tPython"# \d 匹配数字
pattern = r"\d+"
matches = re.findall(pattern, text)
print("数字匹配:", matches)# \w 匹配单词字符(字母、数字、下划线)
pattern = r"\w+"
matches = re.findall(pattern, text)
print("单词字符匹配:", matches)# \s 匹配空白字符
pattern = r"\s+"
matches = re.findall(pattern, text)
pri
http://www.dtcms.com/a/347115.html

相关文章:

  • goland编译过程加载dll路径时出现失败
  • 【golang】ORM框架操作数据库
  • 8.23 JavaWeb(登录 P156-P170)
  • 什么是多元线性回归,系数、自变量、因变量是什么,多元线性回归中的线性是什么
  • 【KO】前端面试五
  • yolo训练实例python篇(二)
  • Python训练营打卡 DAY 45 Tensorboard使用介绍
  • 【Golang】有关垃圾收集器的笔记
  • four people game
  • 【卷积神经网络详解与实例】1——计算机中的图像原理
  • 文件系统挂载详细分析(《图解Linux内核》虚拟文件系统篇笔记二)
  • 详细介绍将 AList 搭建 WebDav 添加到 PotPlayer 专辑 的方法
  • 基于Kubernetes StatefulSet的有状态微服务部署与持久化存储实践经验分享
  • JH-14回柱绞车优化设计cad+设计说明书+绛重
  • (论文速读)OverLoCK -上下文混合动态核卷积
  • OSI参考模型TCP/IP模型 二三事
  • 深入理解Web服务与HTTP协议
  • 55 C++ 现代C++编程艺术4-元编程
  • 总结:Maven多仓库多镜像源配置
  • 26.内置构造函数
  • STM32F1 USART介绍及应用
  • 【读书笔记】《从0到1》
  • MacOS + Android Studio:将 Git 仓库从 HTTP 切换为 SSH 并解决权限问题
  • VLOOKUP专题训练
  • 【Win】Motrix+Aria2浏览器下载加速
  • DeepSeek V3.1 横空出世:重新定义大语言模型的边界与可能
  • Qt5 项目的构建与部署详细讲解
  • 【Android】Fragment生命周期详解
  • 链表漫游指南:C++ 指针操作的艺术与实践
  • 【RK3576】【Android14】Android平台跟文件系统