(http://blog.csdn.net/winterto1990/article/details/47416137)
背景:
re.sub是re模塊重要的組成部分,并且功能也非常強大,主要功能實現(xiàn)正則的替換。
re.sub定義: sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it’s passed the match object and must return a replacement string to be used.
主要的意思為:對字符串string按照正則表達式pattern,將string的匹配項替換成字符串repl。 公式解析: pattern為表示正則中的模式字符串, repl為replacement,被替換的內(nèi)容,repl可以是字符串,也可以是函數(shù)。 string為正則表達式匹配的內(nèi)容。 count:由于正則表達式匹配到的結(jié)果是多個,使用count來限定替換的個數(shù)(順序為從左向右),默認值為0,替換所有的匹配到的結(jié)果。 flags是匹配模式,可以使用按位或’|’表示同時生效,也可以在正則表達式字符串中指定。(詳情見鏈接)
舉例:
>import re
>re.sub(r'\w+','10',"ji 43 af,geq",2,flags=re.I)
'10 10 af,geq'
詳解:首先導入re模塊,使用re.sub函數(shù),r’\w+’為正則表達式,匹配英文單詞或數(shù)字,’10’為被替換的內(nèi)容,”ji 43 af,geq”為re匹配的字符串內(nèi)容,count為2 只替換前兩個,flags=re.I 忽略大小寫。 輸出部分自行理解