Python--正则表达式

Python正则表达式

最近由于工作需要,在学习Python教程中的正则表达式。

参考书籍:《Python编程快速上手------让繁琐工作自动化》

正则表达式是用于字符串搜索和替换的一种强大工具。在 python中,通过 re 模块来实现正则表达式的功能。

基础用法

  • \d:匹配一个数字。
  • \d\d\d\d:匹配连续的四个数字。
  • \d{4}:与上面相同,是简写形式

编译正则表达式

python 复制代码
import re

# 创建正则表达式对象
phoneNumberRegex = re.compile(r'\d{3}-\d{4}-\d{4}')

搜索和匹配

python 复制代码
msg = 'my phone number is: 153-2025-8888, 133-8956-5585'
mo = phoneNumberRegex.search(msg)
print(mo.group())  # 输出匹配的号码

分组

使用括号可以创建分组,匹配的内容可以在分组中获取。

python 复制代码
phoneNumberRegex = re.compile(r'(\d{3})-(\d{4})-(\d{4})')
mo = phoneNumberRegex.search(msg)
areaCode, mainNumber = mo.groups()
print(areaCode)  # 输出区号
print(mainNumber)  # 输出电话号码

高级特性

管道符 |

用于匹配多个表达式中的一个。

python 复制代码
heroRegex = re.compile(r'Batman|Tina Fey')
mo = heroRegex.search('Bat and Tina Fey')
print(mo.group())  # 输出第一个匹配项

可选匹配 ?

匹配前面的子表达式零次或一次。

python 复制代码
batRegex = re.compile(r'Bat(wo)?man')
mo = batRegex.search("The Adventure of Batman")
print(mo.group())  # 输出 Batman 或 Batwoman

星号 *

匹配前面的子表达式零次或多次。

python 复制代码
batRegex = re.compile(r'Bat(wo)*man')
mo = batRegex.search("The Adventure of Batwowowoman")
print(mo.group())  # 输出 Batwoman 或 Batwowowoman

加号 +

匹配前面的子表达式一次或多次。

python 复制代码
batRegex = re.compile(r'Bat(wo)+man')
mo = batRegex.search("The Adventure of Batwoman")
print(mo.group())  # 输出 Batwoman 或 Batwowowoman

指定次数 {}

匹配前面的子表达式特定次数。

python 复制代码
batRegex = re.compile(r'Bat(wo){3}man')
mo = batRegex.search("The Adventure of Batwowowoman")
print(mo.group())  # 输出 Batwowowoman

贪心和非贪心匹配

正则表达式中的贪心匹配会尽可能多地匹配文本,而非贪心匹配则尽可能少地匹配。

python 复制代码
# 贪心匹配
greedyHaRegex = re.compile(r'(Ha){3,5}')
mo1 = greedyHaRegex.search('HaHaHaHaHa')
print('贪心: ' + mo1.group())  # 输出 HaHaHaHaHa

# 非贪心匹配
non_greedyHaRegex = re.compile(r'(Ha){3,5}?')
mo1 = non_greedyHaRegex.search('HaHaHaHaHa')
print('非贪心: ' + mo1.group())  # 输出 HaHaHa

findall() 方法

findall() 方法返回一个包含所有匹配项的列表。

python 复制代码
phoneNumberRegex = re.compile(r'\d{3}-\d{3}-\d{4}')
mo = phoneNumberRegex.findall('Cell: 415-555-1234, Work:215-555-9966')
for number in mo:
    print(number)

分组

使用括号可以创建分组,匹配的内容可以在分组中获取。

python 复制代码
phoneNumberRegex = re.compile(r'(\d{3})-(\d{3})-(\d{4})')
mo = phoneNumberRegex.findall('Cell: 415-555-1234, Work:215-555-9966')
for areaCode, mainNumber in mo:
    print(f'Area Code: {areaCode}, Main Number: {mainNumber}')

特殊字符类

  • \d:匹配一个数字。
  • \D:匹配除了数字外的任意字符。
  • \w:匹配字母、数字和下划线。
  • \W:匹配除了字母、数字和下划线外的任意字符。
  • \s:匹配空白字符(空格、制表符、换行符等)。
  • \S:匹配非空白字符。
python 复制代码
vowelRegex = re.compile(r'[aeiouAEIOU]')
ret = vowelRegex.findall('RoboCop eats baby food. BABY FOOD')
print(ret)

rangeRegex = re.compile(r'[a-zA-Z0-9]')
ret = rangeRegex.findall('we~@@##jEoig012')
print(ret)

noneVowelRegex = re.compile(r'[^aeiouAEIOU]')
ret = noneVowelRegex.findall('RoboCop eats baby food. BABY FOOD')
print(ret)

定位符

  • ^:匹配字符串的开头。
  • $:匹配字符串的结尾。
python 复制代码
beginWithHello = re.compile(r'^Hello')
ret = beginWithHello.search('Hello World')
print(ret.group())

endWithBye = re.compile(r'Bye$')
ret = endWithBye.search('Goodbye for now, Bye')
print(ret.group())

通配符

  • .:匹配除换行符以外的任意字符。
  • *:匹配前面的子表达式零次或多次。
python 复制代码
atRegex = re.compile(r'.at')
ret = atRegex.findall('The cat in that sat on the flat mat')
print(ret)

nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
ret = nameRegex.search('First Name: Al Last Name: Sweigart')
print(ret.group(1))
print(ret.group(2))

re.DOTALL 标志

re.DOTALL 标志允许 . 匹配包括换行符在内的任意字符。

python 复制代码
NewlineRegex = re.compile('.*', re.DOTALL)
ret = NewlineRegex.search('Serve the public trust. \nProtect the innocent.\nUphold the law.')
print(ret.group())
相关推荐
6+h21 小时前
【Spring】AOP核心之原始对象与代理对象
java·python·spring
w_a_o21 小时前
传统配方+机器学习:福尔蒂新材料用15年经验构建梯度回归预测模型(Python开源预告)
python·机器学习·回归·kmeans·宽度优先
jiet_h21 小时前
Python tempfile 深入实战:安全、优雅地处理临时文件与临时目录
python
摩尔曼斯克的海21 小时前
力扣面试题--双指针类
python·算法·leetcode
witAI21 小时前
gemini3.1拆短剧2025解析,多模态模型如何重塑内容创作流程
人工智能·python
love530love21 小时前
Windows 11 源码编译 vLLM 0.16 完全指南(CUDA 12.6 / PyTorch 2.7.1+cu126)
人工智能·pytorch·windows·python·深度学习·comfyui·vllm
zach01271 天前
GEO优化的算力贫困悖论:基于数字地缘政治的量子搜索语义重构
人工智能·python·重构
AsDuang1 天前
Python 3.12 MagicMethods - 28 - __rsub__
开发语言·python
李可以量化1 天前
用 KMeans 聚类寻找股票支撑位与压力位(上):基于 QMT 量化平台实现
python·量化 qmt ptrade
所谓伊人,在水一方3331 天前
【Python数据科学实战之路】第12章 | 无监督学习算法实战:聚类与降维的奥秘
python·sql·学习·算法·信息可视化·聚类