第七天 正则表达式

正则表达式(Regular Expressions,简称 regex)是一种强大的文本处理工具,它允许你定义搜索模式,并基于这些模式在字符串中查找、替换或提取特定的文本片段。Python 提供了内置的 re 模块来支持正则表达式的操作。

以下是一些 Python 中使用正则表达式的常见方法和示例:

导入 re 模块

首先,你需要导入 re 模块:

python 复制代码
import re

基本用法

1. 匹配字符串

使用 re.match() 函数从字符串的起始位置匹配模式。如果匹配成功,返回一个匹配对象;否则返回 None

python 复制代码
pattern = r'\d+'  # 匹配一个或多个数字
text = "123 abc"

match = re.match(pattern, text)
if match:
    print("Match found:", match.group())  # 输出: Match found: 123
else:
    print("No match")
2. 搜索字符串

使用 re.search() 函数在字符串中搜索模式,返回第一个匹配项。

python 复制代码
pattern = r'\d+'
text = "abc 123 def 456"

search = re.search(pattern, text)
if search:
    print("Search found:", search.group())  # 输出: Search found: 123
else:
    print("No search found")
3. 查找所有匹配项

使用 re.findall() 函数查找字符串中所有匹配项,返回一个列表。

python 复制代码
pattern = r'\d+'
text = "abc 123 def 456 ghi 789"

matches = re.findall(pattern, text)
print("All matches:", matches)  # 输出: All matches: ['123', '456', '789']
4. 替换字符串

使用 re.sub() 函数替换字符串中所有匹配项。

python 复制代码
pattern = r'\d+'
text = "abc 123 def 456 ghi 789"

replaced_text = re.sub(pattern, 'XXX', text)
print("Replaced text:", replaced_text)  # 输出: Replaced text: abc XXX def XXX ghi XXX

常用正则表达式模式

  • . : 匹配除换行符以外的任意字符。
  • ^ : 匹配字符串的开始。
  • $ : 匹配字符串的结尾。
  • * : 匹配前一个字符0次或多次。
  • + : 匹配前一个字符1次或多次。
  • ? : 匹配前一个字符0次或1次。
  • {n} : 匹配前一个字符恰好n次。
  • {n,} : 匹配前一个字符至少n次。
  • {n,m} : 匹配前一个字符至少n次,至多m次。
  • [] : 字符集,匹配括号内的任意字符。
  • | : 或,匹配左右表达式中的任意一个。
  • () : 分组,用于提取匹配的子字符串。
  • \d : 匹配一个数字字符(0-9)。
  • \D : 匹配一个非数字字符。
  • \w : 匹配一个字母、数字或下划线字符。
  • \W : 匹配一个非字母、非数字或非下划线字符。
  • \s : 匹配一个空白字符(如空格、制表符等)。
  • \S : 匹配一个非空白字符。

示例:复杂模式

假设你有一个字符串,包含邮箱地址,你想提取所有的邮箱地址:

python 复制代码
text = "Contact us at support@example.com or marketing@test.org for more info."
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'

emails = re.findall(pattern, text)
print("Emails found:", emails)  # 输出: Emails found: ['support@example.com', 'marketing@test.org']

编译正则表达式

为了提高性能,你可以使用 re.compile() 编译正则表达式模式,然后使用该编译后的模式进行匹配、搜索或替换操作。

python 复制代码
pattern = re.compile(r'\d+')
text = "abc 123 def 456"

search = pattern.search(text)
if search:
    print("Search found:", search.group())  # 输出: Search found: 123

正则表达式是一个非常强大的工具,可以帮助你高效地处理字符串。希望这些示例能帮助你理解如何在 Python 中使用正则表达式。

相关推荐
水木流年追梦9 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
水木流年追梦20 小时前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
IT大白鼠2 天前
2019年Cloudflare全球宕机事件技术分析:正则表达式回溯失控与互联网基础设施脆弱性研究
运维·正则表达式·去中心化
XMYX-04 天前
33 - Go 文本模板 template:从入门到原理深挖
golang·正则表达式
XMYX-04 天前
32 - Go 正则表达式:从匹配字符串到理解 RE2 引擎
golang·正则表达式
程序员榴莲5 天前
Python 正则表达式入门:从匹配手机号到提取文本内容
python·正则表达式
红茶要加冰7 天前
七、正则表达式
linux·运维·正则表达式·shell
Pocker_Spades_A7 天前
Python快速入门专业版(五十八)——正则表达式(re):爬虫文本提取利器(从语法到实战)
爬虫·python·正则表达式
红茶要加冰7 天前
九、文本处理三剑客——sed
linux·运维·服务器·正则表达式·shell
Bug-制造者7 天前
正则表达式 vs Shell通配符:彻底分清,告别命令行踩坑
linux·正则表达式