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' ('', '', '')
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
相关推荐
wangzhaotongalex 2020-10-20
wyq 2020-11-11
TLROJE 2020-10-26
风雨断肠人 2020-10-13
duanqingfeng 2020-09-29
rechanel 2020-11-16
cshanzhizi 2020-10-16
luofuIT成长记录 2020-09-22
phphub 2020-09-10
taomengxing 2020-09-07
MaggieRose 2020-08-19
flyingssky 2020-08-18
山水沐光 2020-08-18
jyj00 2020-08-15
AHuqihua 2020-08-09
山水沐光 2020-08-03