亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 正则表达式精通:re.match、re.search、re.findall 实战详解

什么是 Python 正则表达式?

正则表达式(regex) 是一种紧凑的文本模式描述,告诉 Python 如何在字符串中定位模式。正则在数据提取、验证、转换等场景(代码库、日志、配置文件、网页抓取)中不可或缺。

Python 标准库 re 模块提供了编译模式、搜索、替换的丰富 API。无论是过滤用户输入、解析日志还是抓取网页内容,扎实的正则基础都能节省时间、减少 Bug。

核心正则概念

常用标识符对照表

标识符说明空白字符特殊转义
\d任意数字(0-9)\n., +, *, ?, [], $, ^, (, ), {}, |, \
\D非数字\s
\s空格、制表、换行等\t
\S非空白\e
\w字母数字加下划线\r
\W非字母数字(不含下划线)\f
.除换行外任意字符—
\b单词边界—
\.字面点号—
\{x}恰好 x 次—

开始使用 re 模块

import re

re 模块属于标准库,无需外部依赖。常见用例:

示例 1:\w+ 与 ^

可捕获字符串首个单词:

import re
sample = "guru99, education is fun"
result = re.findall(r"^\w+", sample)
print(result)  # Output: ['guru99']

去掉 + 仅返回首字符:["g"]。

示例 2:用 \s 分割空白字符

re.split() 可按模式分割字符串。\s 匹配任意空白字符。

import re
text = "we are splitting the words"
print(re.split(r"\s", text))  # ['we', 'are', 'splitting', 'the', 'words']

若省略反斜杠,s 视为字面字符,导致在每个 s 处分割。

正则方法概览

使用 re.match()

import re
text = "guru99 is a great platform"
match = re.match(r"^\w+", text)
print(match.group() if match else "No match")  # Output: guru99

使用 re.search()

import re
text = "Software Testing is fun"
for pattern in ["Software testing", "guru99"]:
    found = re.search(pattern, text, re.IGNORECASE)
    print(f"Looking for '{pattern}' in '{text}' - {'found a match!' if found else 'no match'}")

使用 re.findall()

import re
emails = "guru99@google.com, careerguru99@hotmail.com, users@yahoomail.com"
found = re.findall(r"[\w\.-]+@[\w\.-]+", emails)
for e in found:
    print(e)

正则标志位

标志位修改模式行为。常用标志:

标志说明
re.M (re.MULTILINE)使 ^ 和 $ 匹配每行开头结尾
re.I (re.IGNORECASE)忽略大小写
re.S (re.DOTALL)使 . 匹配换行符
re.U (re.UNICODE)启用 Unicode 感知字符类
re.L (re.LOCALE)字符类依赖当前区域设置
re.X (re.VERBOSE)允许模式中包含空白和注释

多行模式示例

import re
text = """guru99
careerguru99
selenium"""
print(re.findall(r"^\w", text))           # ['g']
print(re.findall(r"^\w", text, re.MULTILINE))  # ['g', 'c', 's']

Python 2 兼容性

以上示例基于 Python 3。若需在 Python 2 运行,请将 print() 改为 Python 2 语法,re 模块导入方式相同。

核心要点

Python

  1. Python 正则表达式 (re 模块) 实战指南
  2. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  3. Python str.count() 完全指南:统计字符与子串出现次数实战
  4. Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
  5. Python len() 函数实战指南:测量字符串、列表、元组、字典等对象长度
  6. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  7. Python round() 函数详解与实战示例
  8. 精通 Python map() 函数:语法、示例与最佳实践
  9. Python timeit():精准测量代码执行时间与实战示例
  10. Python collections.Counter:高效计数、更新与算术运算
  11. Python list.count() 专家指南:语法、示例与性能解析
  12. Python list.index() 详解:查找元素位置的实用指南与示例