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())
相关推荐
ID_180079054731 天前
基于 Python 的 Cdiscount 商品详情 API 调用与 JSON 核心字段解析(含多规格 SKU 提取)
开发语言·python·json
Q_Q5110082851 天前
python+django/flask+vue的大健康养老公寓管理系统
spring boot·python·django·flask·node.js
我是哈哈hh1 天前
【Python数据分析】Numpy总结
开发语言·python·数据挖掘·数据分析·numpy·python数据分析
Michelle80231 天前
24大数据 14-2 函数练习
开发语言·python
qq_381454991 天前
Python学习技巧
开发语言·python·学习
Ndmzi1 天前
Matlab编程技巧:自定义Simulink菜单(理解补充)
前端·javascript·python
dagouaofei1 天前
AI生成个性化年终总结PPT
人工智能·python·powerpoint
white-persist1 天前
VSCode 快捷键大全:从设计理念到场景化高效运用(详细解析)(文章末尾有vim快捷键大全)
linux·ide·vscode·python·编辑器·系统安全·vim
liliangcsdn1 天前
python threading异步并发调用示例
python
计算机毕设匠心工作室1 天前
【python大数据毕设实战】全面皮肤病症状数据可视化分析系统、Hadoop、计算机毕业设计、包括数据爬取、数据分析、数据可视化、机器学习、实战教学
后端·python·mysql