详解python里使用正则表达式的分组命名方式

yipeiwu_com5年前Python基础

详解python里使用正则表达式的分组命名方式

分组匹配的模式,可以通过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'}

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

python实现无证书加密解密实例

本文实例讲述了python实现无证书加密解密的方法,分享给大家供大家参考。具体实现方法如下: 无证书加密就是双方不需要维护证书,加密与解密只需要双方约定一个key就可以,无证书加解密的方...

python查找指定文件夹下所有文件并按修改时间倒序排列的方法

代码如下: import os, glob, time def search_all_files_return_by_time_reversed(path, reverse=Tru...

对python插入数据库和生成插入sql的示例讲解

如下所示: #-*- encoding:utf-8 -*- import csv import sys,os import pymysql def read_csv(filen...

python进阶之多线程对同一个全局变量的处理方法

通常情况下: from threading import Thread global_num = 0 def func1(): global global_num for...

Django生成PDF文档显示网页上以及PDF中文显示乱码的解决方法

Django生成PDF文档显示网页上以及PDF中文显示乱码的解决方法

项目地址:https://github.com/PythonerKK/django-generate-pdf/tree/master 这个demo实现了通过用户输入自己的个人信息生成一份...