第七天 正则表达式

正则表达式(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 中使用正则表达式。

相关推荐
疯狂吧小飞牛1 天前
正则表达式特殊字符
正则表达式
White graces1 天前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
astragin1 天前
正则表达式常用记录
正则表达式
不会玩技术的技术girl1 天前
使用Python和正则表达式爬取网页中的URL数据
开发语言·python·正则表达式
疯狂吧小飞牛1 天前
正则表达式–断言
正则表达式
yuanbenshidiaos1 天前
【正则表达式】
数据库·mysql·正则表达式
奔跑吧邓邓子2 天前
【Python爬虫(12)】正则表达式:Python爬虫的进阶利刃
爬虫·python·正则表达式·进阶·高级
阿华的代码王国2 天前
【从0做项目】Java搜索引擎(6)& 正则表达式鲨疯了&优化正文解析
java·后端·搜索引擎·正则表达式·java项目·从0到1做项目
程序员小王꧔ꦿ3 天前
BeautifulSoup、lxml/XPath和正则表达式在数据爬取中的核心差异及适用场景
正则表达式·beautifulsoup
程序员小王꧔ꦿ3 天前
BeautifulSoup、lxml/XPath和正则表达式在数据爬取中的适用场景
正则表达式·beautifulsoup