佚名通过本文主要向大家介绍了python 正则表达式,python正则表达式教程,python正则表达式语法,python3 正则表达式,python中正则表达式等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
问题:python正则表达式不理解?
描述:
解决方案1:
描述:
我在看python正则表达是正则指南时对这里有点不理解
p = re.compile(r'\W+')
p.split('This... is a test.')
结果是
['This', 'is', 'a', 'test', '']
但是预编译改为re.compile(r'(\W+)')
后,输出为什么变为了
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
()是用来分组的还有其他的作用吗?这个该怎么理解。
解决方案1:
加括号后表示分组,会匹配\W+,并捕获匹配的文本到组中
re.split函数的定义,参考python文档7.2. re — Regular expression operations
If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list.
即被捕获的文本也会被插入结果列表后返回。
加了?:后就不会捕获匹配文本到组中,re.compile(r'(?:\W+)')
,结果就和第一种情况一样