Python正则匹配r'\s+'与r'(\s+)'两种方法有何不同,python有何不同,上代码:import r


上代码:

import res = 'a b c d e're.split(r'\s+', s)      # 结果: ['a', 'b', 'c', 'd', 'e']re.split(r'(\s+)', s)    # 结果: ['a', ' ', 'b', ' ', 'c', ' ', 'd', ' ', 'e']

感觉与正则引擎规则有关.这其中差别的原因到底是因为什么?求指教.

http://docs.python.org/2/library/re.html#re.split

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.

如评论所说,看过文档了你还问?!

再来一个例子,可以帮助更好的理解这个问题:

>>> s = 'a12b12c'>>> re.split(r'(1)(2)', s)['a', '1', '2', 'b', '1', '2', 'c']>>> re.split(r'((1)(2))', s)['a', '12', '1', '2', 'b', '12', '1', '2', 'c']

如果你的正则表达式中确实必须使用括号,但又不想把括号匹配到的部分包含在结果当中,记得使用非捕获分组(non-capturing group)的语法:

>>> re.split(r'(?:1)(2)', s)['a', '2', 'b', '2', 'c']

编橙之家文章,

评论关闭