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

yipeiwu_com6年前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 语音识别框架详解

如下所示: from win32com.client import constants import os import win32com.client import pythonc...

Python实现PS图像抽象画风效果的方法

Python实现PS图像抽象画风效果的方法

本文实例讲述了Python实现PS图像抽象画风效果的方法。分享给大家供大家参考,具体如下: 今天介绍一种基于图像分割和color map 随机采样生成一种抽象画风的图像特效,简单来说,就...

为Python的web框架编写MVC配置来使其运行的教程

为Python的web框架编写MVC配置来使其运行的教程

现在,ORM框架、Web框架和配置都已就绪,我们可以开始编写一个最简单的MVC,把它们全部启动起来。 通过Web框架的@decorator和ORM框架的Model支持,可以很容易地编写一...

Django Admin中增加导出Excel功能过程解析

Django Admin中增加导出Excel功能过程解析

在使用Django Admin时, 对于列表我们有时需要提供数据导出功能, 如下图: 增加导出Excel功能 在Django Admin中每个模型的Admin类(继承至admin.M...

浅谈django orm 优化

orm优化 1.数据库技术进行优化,包括给字段加索引,设置唯一性约束等等; 2.查询过滤工作在数据库语句中做,不要放在代码中完成(看情况); 3.如果要一次查询出集合的数量,使用c...