python正则表达式不理解?

我在看python正则表达是正则指南时对这里有点不理解

p = re.compile(r'\W+')
p.split('This... is a test.')

结果是

['This', 'is', 'a', 'test', '']

但是预编译改为re.compile(r'(\W+)')后,输出为什么变为了

['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

()是用来分组的还有其他的作用吗?这个该怎么理解。

阅读 3.8k
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+)'),结果就和第一种情况一样

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进