上代码:
import re
s = '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']
感觉与正则引擎规则有关.这其中差别的原因到底是因为什么?求指教.
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如评论所说,看过文档了你还问?!
再来一个例子,可以帮助更好的理解这个问题:
如果你的正则表达式中确实必须使用括号,但又不想把括号匹配到的部分包含在结果当中,记得使用非捕获分组(non-capturing group)的语法:
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.