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())
相关推荐
大佬,救命!!!44 分钟前
整理python快速构建数据可视化前端的Dash库
python·信息可视化·学习笔记·dash·记录成长
孔丘闻言1 小时前
python调用mysql
android·python·mysql
Teletele-Lin1 小时前
Miniconda安装与VSCode搭建远程Python、Jupyter开发环境
vscode·python·jupyter·环境配置·远程开发
伊玛目的门徒2 小时前
告别 OpenAI SDK:如何使用 Python requests 库调用大模型 API(例如百度的ernie-4.5-turbo)
python·openai·requests·大模型调用·ernie-4.5-turbo
sinat_602035363 小时前
模块与包的导入
运维·服务器·开发语言·python
计算机学姐3 小时前
基于Python的旅游数据分析可视化系统【2026最新】
vue.js·后端·python·数据分析·django·flask·旅游
恋雨QAQ3 小时前
python函数和面向对象
开发语言·python
天雪浪子3 小时前
Python入门教程之逻辑运算符
开发语言·python
张子夜 iiii3 小时前
实战项目-----在图片 hua.png 中,用红色画出花的外部轮廓,用绿色画出其简化轮廓(ε=周长×0.005),并在同一窗口显示
人工智能·pytorch·python·opencv·计算机视觉