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

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

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

例如写如下的测试代码:

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

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


使用了括号,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

【热门文章】
【热门文章】