Python3正则表示式(3)
2024-09-20 18:45:44
正则表示式对象
对象1:
案例1:
import re
example = 'ShanDong Institute of Business and Technology'
pattern = re.compile(r'\bB\w+\b') # 查找以B开头的单词
pattern.findall(example)
# 结果:['Business']
pattern = re.compile(r'\w+g\b') # 查找以字母g结尾的单词
pattern.findall(example)
# 结果:['ShanDong']
pattern = re.compile(r'\b[a-zA-Z]{3}\b') # 查找3个字母长的单词
pattern.findall(example)
# 结果:['and']
pattern.search(example)
# 结果:<_sre.SRE_Match object; span=(31, 34), match='and'>
pattern = re.compile(r'\b\w*a\w*\b') # 查找所有含字母a的单词
pattern.findall(example)
# 结果:['ShanDong', 'and'] text = 'He was carefully disguised but captured quickly by police.'
re.findall(r'\w+ly', text) # 查找所有以字母组合ly结尾的单词
# 结果:['carefully', 'quickly']
对象2
案例2:
example = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.""" pattern = re.compile(r'\bb\w*\b', re.I)
print(pattern.sub('*', example))
# 结果
'''
* is * than ugly.
Explicit is * than implicit.
Simple is * than complex.
Complex is * than complicated.
Flat is * than nested.
Sparse is * than dense.
Readability counts.
'''
print(pattern.sub(lambda x: x.group(0).upper(), example))
# 结果
'''
BEAUTIFUL is BETTER than ugly.
Explicit is BETTER than implicit.
Simple is BETTER than complex.
Complex is BETTER than complicated.
Flat is BETTER than nested.
Sparse is BETTER than dense.
Readability counts.
'''
print(pattern.sub('#', example, 1))
# 结果
'''
# is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
'''
对象3
知识在于点点滴滴的积累,我会在这个路上Go ahead,
有幸看到我博客的朋友们,若能学到知识,请多多关注以及讨论,让我们共同进步,扬帆起航。
后记:打油诗一首
适度锻炼,量化指标
考量天气,设定目标
科学锻炼,成就体标
高效科研,实现学标
最新文章
- Java学习——连接数据库
- SQL Server自动化运维系列——批量执行SQL脚本(Power Shell)
- UWP&;WP8.1 重新绘制图片 WriteableBitmap用法 图片转byte[]数组,byte[]数组转图片
- shell脚本调试
- Java中的链表数据结构
- 《TCP/IP详解 卷一》读书笔记-----TCP数据流
- 用ie调试的时候显示:脚本调试程序无法连接到目标进程,已附加调试程序。
- Mysql大数据量查询优化
- 云服务器 ECS Linux 系统添加“回收站”
- How to Run Node.js with Express on Mobile Devices
- 初学c++
- CSS Hack (各个浏览器兼容的问题)
- OOAD基本概念
- java udp socket通信(仅发送)
- Vue.js 基础指令实例讲解(各种数据绑定、表单渲染大总结)——新手入门、高手进阶
- PHP高并发
- Analysis Services(SSAS) 性能优化
- 让wampserver2.5.exe支持sql server数据库的方法
- mod_fcgid: HTTP request length 136136 (so far) exceeds MaxRequestLen (131072)
- 周鸿祎与85后的座谈(一):人人需要Mentor,世界没有奇迹