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())
相关推荐
某人辛木8 分钟前
Web自动化测试
前端·python·pycharm·pytest
C+++Python30 分钟前
详细介绍一下Java泛型的通配符
java·windows·python
小帅热爱难回头1 小时前
编写Skill生成AI落地项目系统架构
python
diving deep2 小时前
脚本速览-python
开发语言·python
2601_951643773 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
AC赳赳老秦5 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
茉莉玫瑰花茶7 小时前
综合案例 - AI 智能租房助手 [ 5 ]
服务器·数据库·人工智能·python·ai
文艺倾年7 小时前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型
宸丶一7 小时前
Day 13:持久化记忆 - 让 Agent 拥有长期记忆
jvm·python·ai
码云骑士8 小时前
13-列表append的底层真相(上)-listobject源码中的预分配策略
开发语言·python