將字符串分片

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.']
相關文章
相關標籤/搜索