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' ('', '', '')

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

相关文章

对Python3之方法的覆盖与super函数详解

对Python3之方法的覆盖与super函数详解

#覆盖 覆盖:在继承关系中,子类实现了与基类同名的方法,在子类的实例调用该方法时,实例调用的是子类的覆盖版本。 通俗的讲,就是小明继承了他⑧的自行车,经过自己的改装,成了电动车,那么小明...

Python下使用Psyco模块优化运行速度

今天介绍下Psyco模块,Psyco模块可以使你的Python程序运行的像C语言一样快。 都说Python语言易用易学,但性能上跟一些编译语言(如C语言)比较要差不少,这里可以用C语言和...

python实现电子书翻页小程序

python实现电子书翻页小程序

本文实例为大家分享了python实现电子书翻页的具体代码,供大家参考,具体内容如下 1.题目: 电子书翻页: (1)自动翻页:每次默认读三行,读完之后睡两秒,直到把所有内容全部读出来 (...

python 实现将txt文件多行合并为一行并将中间的空格去掉方法

有一个txt文本如下: 151 151 1234561 156421 214156 1523132 031320 现希望将两行合并为一行,并将中间所有的空格都去掉: (pyth...

浅谈Python 集合(set)类型的操作——并交差

阅读目录 •介绍 •基本操作 •函数操作 介绍 python的set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交...