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

yipeiwu_com5年前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类方法__init__和__del__构造、析构过程分析

最近学习《Python参考手册》学到Class部分,遇到了类的构造析构部分的问题: 1、什么时候构造? 2、什么时候析构? 3、成员变量如何处理? 4、Python中的共享成员函数如何访...

python变量赋值方法(可变与不可变)

python变量赋值方法(可变与不可变)

python中不存在所谓的传值调用,一切传递的都是对象的引用,也可以认为是传址。 一、可变对象和不可变对象 Python在heap中分配的对象分成两类:可变对象和不可变对象。所谓可变对象...

Linux下用Python脚本监控目录变化代码分享

#!/usr/bin/env python #coding=utf-8 import os from pyinotify import WatchManager, Notifier...

python difflib模块示例讲解

python difflib模块示例讲解

difflib模块提供的类和方法用来进行序列的差异化比较,它能够比对文件并生成差异结果文本或者html格式的差异化比较页面,如果需要比较目录的不同,可以使用filecmp模块。 clas...

Python PyCharm如何进行断点调试

Python PyCharm如何进行断点调试

编辑器不等于IDE(集成开发环境),开发python程序,不是只有一种print()打印输出调试。 术业有专攻,于人如此,于一个软件也是如此。让专业的软件做专业的事。 以上两点得出的结论...