Python中正则表达式"()"的疑问

在复习正则表达式的时候,不太理解"\W+"和"(\W+)"之间的区别.

例如写如下的测试代码:

>>> re.split('\W+', "helo, world, words")
['helo', 'world', 'words']
>>> re.split('(\W+)', "helo, world, words")
['helo', ', ', 'world', ', ', 'words']

不太理解第二个括号中,为什么会把空白字符给筛选出来.

阅读 1.9k
1 个回答

使用了括号,python就会把识别出来的划分符也当成结果的一部分返回,
在你的例子中就是那些连续的非字母数字字符", "

官方文档:

 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.

参考: https://docs.python.org/2/library/re.html#re.split

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