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', '.', '']

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

python3.x 正则表达式

开挂玩扫雷 10 years ago

加括号后表示分组,会匹配\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+)') ,结果就和第一种情况一样

佐尔法格哈 answered 10 years ago

Your Answer