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 控制语句

1比如python提倡简单实用的思想,它就没有switch语句,如果要实现switch语句的效果 的话可以通过2个方法来写把 (1)通过if elif 语句来实现 if 条件: … el...

高效测试用例组织算法pairwise之Python实现方法

高效测试用例组织算法pairwise之Python实现方法

开篇: 测试过程中,对于多参数参数多值的情况进行测试用例组织,之前一直使用【正交分析法】进行用例组织,说白了就是把每个参数的所有值分别和其他参数的值做一个全量组合,用Python脚本实现...

Python实现扫描指定目录下的子目录及文件的方法

本文介绍了使用Python来扫描指定目录下的文件,或者匹配指定后缀和前缀的函数。步骤如下: 如果要扫描指定目录下的文件,包括子目录,需要调用scan_files("/export/hom...

python基础教程之类class定义使用方法

面对对象(oop)中的对象,是一个非常重要的知识点,我们可以把它简单看做是数据以及由存取、操作这些数据的方法所组成的一个集合。我们在学习函数(function)之后,知道了如果重用代码,...

Python代码实现删除一个list里面重复元素的方法

网上学习了的两个新方法,代码非常之简洁。看来,不是只要实现了基本功能就能交差滴,想要真的学好python还有很长的一段路呀 方法一:是利用map的fromkeys来自动过滤重复值,map...