python里使用正则表达式的组嵌套实例详解

yipeiwu_com4年前Python基础

python里使用正则表达式的组嵌套实例详解

由于组本身是一个完整的正则表达式,所以可以将组嵌套在其他组中,以构建更复杂的表达式。下面的例子,就是进行组嵌套的例子:

#python 3.6 
#蔡军生  
#http://blog.csdn.net/caimouse/article/details/51749579 
# 
import re 
 
 
def test_patterns(text, patterns): 
  """Given source text and a list of patterns, look for 
  matches for each pattern within the text and print 
  them to stdout. 
  """ 
  # Look for each pattern in the text and print the results 
  for pattern, desc in patterns: 
    print('{!r} ({})\n'.format(pattern, desc)) 
    print(' {!r}'.format(text)) 
    for match in re.finditer(pattern, text): 
      s = match.start() 
      e = match.end() 
      prefix = ' ' * (s) 
      print( 
        ' {}{!r}{} '.format(prefix, 
                   text[s:e], 
                   ' ' * (len(text) - e)), 
        end=' ', 
      ) 
      print(match.groups()) 
      if match.groupdict(): 
        print('{}{}'.format( 
          ' ' * (len(text) - s), 
          match.groupdict()), 
        ) 
    print() 
  return 

例子:

#python 3.6 
#蔡军生  
#http://blog.csdn.net/caimouse/article/details/51749579 
# 
from re_test_patterns_groups import test_patterns 
 
test_patterns( 
  'abbaabbba', 
  [(r'a((a*)(b*))', 'a followed by 0-n a and 0-n b')], 
) 

 

结果输出如下:

'a((a*)(b*))' (a followed by 0-n a and 0-n b)


 'abbaabbba'
 'abb'    ('bb', '', 'bb')
   'aabbb'  ('abbb', 'a', 'bbb')
     'a' ('', '', '')

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

相关文章

Python FtpLib模块应用操作详解

本文实例讲述了Python FtpLib模块应用操作。分享给大家供大家参考,具体如下: Python之FtpLib模块应用 工厂中有这样的应用场景: 需要不间断地把设备电脑生成的数据文件...

解决Python使用列表副本的问题

要使用一个列表的副本,要用切片进行列表复制,这样会形成两个独立的列表。 切记不要将列表赋值给一个列表,因为这样并不能得到两个列表。 1、使用赋值语法创建列表副本的问题 下边就将列表赋值,...

Python设置Socket代理及实现远程摄像头控制的例子

为python设置socket代理 首先,你得下载SocksiPy这个.解压出来之后里面会有一个socks.py文件.然后你可以把这个文件复制到python安装目录里面的Lib\site...

python顺序的读取文件夹下名称有序的文件方法

如下所示: import os path="/home/test/" #待读取的文件夹 path_list=os.listdir(path) path_list.sort() #对读...

Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。 关于时间戳的几个概念 时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移...