python里使用正则表达式的分组命名方式
2023-09-14 09:10:36 时间
在前面学习了分组匹配的模式,可以通过groups()来全部访问匹配的元组,也可以通过group()函数来按分组方式来访问,但是这里只能通过数字索引来访问,如果某一天产品经理需要修改需求,让你在它们之中添加一个分组,这样一来,就会导致匹配的数组的索引的变化,作为开发人员的你,必须得一行一行代码地修改。因此聪明的开发人员又想到一个好方法,把这些分组进行命名,只需要对名称进行访问分组,不通过索引来访问了,就可以避免这个问题。那么怎么样来命名呢?可以采用(?P<name>pattern)的格式来命名。例子如下:
#python 3.6
#蔡军生
#http://blog.csdn.net/caimouse/article/details/51749579
#
import re
text = 'This is some text -- with punctuation.'
print(text)
print()
patterns = [
r'^(?P<first_word>\w+)',
r'(?P<last_word>\w+)\S*$',
r'(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)',
r'(?P<ends_with_t>\w+t)\b',
]
for pattern in patterns:
regex = re.compile(pattern)
match = regex.search(text)
print("'{}'".format(pattern))
print(' ', match.groups())
print(' ', match.groupdict())
print()
结果输出如下:
This is some text -- with punctuation.
'^(?P<first_word>\w+)'
('This',)
{'first_word': 'This'}
'(?P<last_word>\w+)\S*$'
('punctuation',)
{'last_word': 'punctuation'}
'(?P<t_word>\bt\w+)\W+(?P<other_word>\w+)'
('text', 'with')
{'t_word': 'text', 'other_word': 'with'}
'(?P<ends_with_t>\w+t)\b'
('text',)
{'ends_with_t': 'text'}
深入浅出Numpy
http://edu.csdn.net/course/detail/6149
Python游戏开发入门
你也能动手修改C编译器
纸牌游戏开发
http://edu.csdn.net/course/detail/5538
五子棋游戏开发
http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672
相关文章
- python的数据结构之栈
- python 图片和base64互相转换
- python的dict,set,list,tuple应用详解
- python标准库学习7
- 第四章 Python运算符和流程控制
- Python时间模块常用 API
- Open3D——点云投影到拟合平面(python详细过程版)
- 华为OD机试 - 新员工座位(Java & JS & Python)
- 华为OD机试 - 最优高铁城市修建方案(Java & JS & Python)
- 3000W个程序员晕了,python学了有什么用?
- Python语言学习之打印输出那些事:python输出图表和各种吊炸天的字符串或图画、版权声明(如README.md)等之详细攻略
- twisted:基于python的twisted框架编写一个客户端和服务端的对话聊天空间
- Py之pymssql:Python库之pymssql的简介、安装、使用方法之详细攻略
- Python 的七大就业方向,总有一个适合你!
- 美女如何无水印下载?python带你批量采集(含完整源码)
- python生成gif
- 【华为机试真题 Python实现】数字字符串组合倒序
- 【 华为OD机试 2023】积木最远距离(C++ Java JavaScript Python)
- Python、PHP:手机号匹配正则表达式
- Python: 正则表达式匹配反斜杠 ""
- python里预先编译正则表达式提高效率
- python里使用正则表达式来替换匹配成功的组并输出替换的次数
- python里使用正则表达式的groups()函数访问组匹配串
- python里使用正则表达式的ASCII模式
- python里使用正则表达式的全匹配功能
- Python 高级编程之正则表达式