正則常見方法梳理
split方法
將一個字符串按照正則表達式匹配結果進行分割,返回結果是列表類型。
- pattern:正則表達式的字符串或原生字符串表示
- string:待匹配字符串
- maxsplit:最大分割數,剩余部分最為最后一個元素輸出
- flags:正則表達式使用時候的控制標記
re模塊的split方法和字符串的split方法很相似,都是利用特定的字符去分割字符串。但是re模塊的split可以使用正則表達式,更加靈活強大。
import retext = 'boxing########basketball##football####ILOVEYOU'
text2 = 'boxing123basketball45football8888ILOVEYOU'
text3 = 'boxing#basketball~football8888ILOVEYOU321小心心'# 這里的正則的+表示量詞,一個或者多個
pattern = r'#+'
pattern2 = r'\d+'
pattern3 = r'\d+|~|#'alist = re.split(pattern, text)
blist = re.split(pattern2, text2)
clist = re.split(pattern3, text3)
print(alist, type(alist))
print(blist, type(blist))
print(clist, type(clist)