Grammar:
re.sub(pattern, repl, string[, count])
使用repl替換string中每一個匹配的子串后返回替換后的字符串。
當repl是一個字符串時,可以使用\id或\g、\g引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。
count用於指定最多替換次數,不指定時全部替換。
re.subn(pattern, repl, string[, count])
返回 (sub(repl, string[, count]), 替換次數)。
Case:
1 #coding=utf-8 2 3 import re 4 5 str = "https://i.cnb1logs.co2m/Edi3tPosts.asp4x?opt=999" 6 7 8 pattern=re.compile(r'(\.)') 9 print '\. :' ,re.sub(pattern,'-',str) 10 11 pattern=re.compile(r'\/([^*]+)\/') 12 print '\/([^*]+)\/ :' ,re.sub(pattern,r'<em>\1<em>',str) 13 14 pattern = re.compile(r'(\w+)(\w+)(\d+)') 15 #先切片測試 16 print re.split(pattern,str) 17 print re.sub(pattern,r'\3 \1',str) 18 #subn統計sub替換次數 19 print re.subn(pattern,r'\3 \1',str)
Output
1 \. : https://i-cnb1logs-co2m/Edi3tPosts-asp4x?opt=999 2 \/([^*]+)\/ : https:<em>/i.cnb1logs.co2m<em>Edi3tPosts.asp4x?opt=999 3 ['https://i.', 'cn', 'b', '1', 'logs.', 'c', 'o', '2', 'm/', 'Ed', 'i', '3', 'tPosts.', 'as', 'p', '4', 'x?opt=', '9', '9', '9', ''] 4 https://i.1 cnlogs.2 cm/3 EdtPosts.4 asx?opt=9 9 5 ('https://i.1 cnlogs.2 cm/3 EdtPosts.4 asx?opt=9 9', 5) 6 7 ***Repl Closed***
quote:http://cuiqingcai.com/977.html