RegexObject
的 split() 方法在 RE 匹配的地方将字符串分片,将返回列表。它同字符串的 split() 方法类似但提供更多的定界符;split()只支持空白符和固定字符串。就象你预料的那样,也有一个模块级的 re.split() 函数。python
split(string [, maxsplit = 0])
经过正则表达式将字符串分片。若是捕获括号在 RE 中使用,那么它们的内容也会做为结果列表的一部分返回。若是 maxsplit 非零,那么最多只能分出 maxsplit 个分片。正则表达式
你能够经过设置 maxsplit 值来限制分片数。当 maxsplit 非零时,最多只能有 maxsplit 个分片,字符串的其他部分被作为列表的最后部分返回。在下面的例子中,定界符能够是非数字字母字符的任意序列。函数
#!python >>> p = re.compile(r'\W+') >>> p.split('This is a test, short and sweet, of split().') ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', ''] >>> p.split('This is a test, short and sweet, of split().', 3) ['This', 'is', 'a', 'test, short and sweet, of split().']
有时,你不只对定界符之间的文本感兴趣,也须要知道定界符是什么。若是捕获括号在 RE 中使用,那么它们的值也会看成列表的一部分返回。比较下面的调用:code
#!python >>> p = re.compile(r'\W+') >>> p2 = re.compile(r'(\W+)') >>> p.split('This... is a test.') ['This', 'is', 'a', 'test', ''] >>> p2.split('This... is a test.') ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']
模块级函数 re.split() 将 RE 做为第一个参数,其余同样。字符串
#!python >>> re.split('[\W]+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split('([\W]+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split('[\W]+', 'Words, words, words.', 1) ['Words', 'words, words.']