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())
相关推荐
AI蜗牛之家2 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk3 小时前
python打卡第48天
开发语言·python
Eiceblue5 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550405 小时前
初级程序员入门指南
javascript·python·算法
程序员的世界你不懂6 小时前
Appium+python自动化(十)- 元素定位
python·appium·自动化
CryptoPP6 小时前
使用WebSocket实时获取印度股票数据源(无调用次数限制)实战
后端·python·websocket·网络协议·区块链
树叶@6 小时前
Python数据分析7
开发语言·python
老胖闲聊7 小时前
Python Rio 【图像处理】库简介
开发语言·图像处理·python
码界奇点8 小时前
Python Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
浠寒AI8 小时前
智能体模式篇(上)- 深入 ReAct:LangGraph构建能自主思考与行动的 AI
人工智能·python