其餘常見的用途就是找到全部模式匹配的字符串並用不一樣的字符串來替換它們。sub() 方法提供一個替換值,能夠是字符串或一個函數,和一個要被處理的字符串。python
sub(replacement, string[, count = 0])
返回的字符串是在字符串中用 RE 最左邊不重複的匹配來替換。若是模式沒有發現,字符將被沒有改變地返回。正則表達式
可選參數 count 是模式匹配後替換的最大次數;count 必須是非負整數。缺省值是 0 表示替換全部的匹配。函數
這裏有個使用 sub() 方法的簡單例子。它用單詞 "colour" 替換顏色名。翻譯
#!python >>> p = re.compile( '(blue|white|red)') >>> p.sub( 'colour', 'blue socks and red shoes') 'colour socks and colour shoes' >>> p.sub( 'colour', 'blue socks and red shoes', count=1) 'colour socks and red shoes'
subn() 方法做用同樣,但返回的是包含新字符串和替換執行次數的兩元組。code
#!python >>> p = re.compile( '(blue|white|red)') >>> p.subn( 'colour', 'blue socks and red shoes') ('colour socks and colour shoes', 2) >>> p.subn( 'colour', 'no colours at all') ('no colours at all', 0)
空匹配只有在它們沒有緊挨着前一個匹配時纔會被替換掉。對象
#!python >>> p = re.compile('x*') >>> p.sub('-', 'abxd') '-a-b-d-'
若是替換的是一個字符串,任何在其中的反斜槓都會被處理。"\n" 將會被轉換成一個換行符,"\r"轉換成回車等等。未知的轉義如 "\j" 則保持原樣。逆向引用,如 "\6",被 RE 中相應的組匹配而被子串替換。這使你能夠在替換後的字符串中插入原始文本的一部分。ci
這個例子匹配被 "{" 和 "}" 括起來的單詞 "section",並將 "section" 替換成 "subsection"。字符串
#!python >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE) >>> p.sub(r'subsection{\1}','section{First} section{second}') 'subsection{First} subsection{second}'
還能夠指定用 (?P<name>...) 語法定義的命名組。"\g<name>" 將經過組名 "name" 用子串來匹配,而且 "\g<number>" 使用相應的組號。因此 "\g<2>" 等於 "\2",但能在替換字符串裏含義不清,如 "\g<2>0"。("\20" 被解釋成對組 20 的引用,而不是對後面跟着一個字母 "0" 的組 2 的引用。)string
#!python >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE) >>> p.sub(r'subsection{\1}','section{First}') 'subsection{First}' >>> p.sub(r'subsection{\g<1>}','section{First}') 'subsection{First}' >>> p.sub(r'subsection{\g<name>}','section{First}') 'subsection{First}'
替換也能夠是一個甚至給你更多控制的函數。若是替換是個函數,該函數將會被模式中每個不重複的匹配所調用。在每次調用時,函數會被傳入一個 MatchObject
的對象做爲參數,所以能夠用這個對象去計算出替換字符串並返回它。it
在下面的例子裏,替換函數將十進制翻譯成十六進制:
#!python >>> def hexrepl( match ): ... "Return the hex string for a decimal number" ... value = int( match.group() ) ... return hex(value) ... >>> p = re.compile(r'\d+') >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.') 'Call 0xffd2 for printing, 0xc000 for user code.'
當使用模塊級的 re.sub() 函數時,模式做爲第一個參數。模式也許是一個字符串或一個RegexObject
;若是你須要指定正則表達式標誌,你必需要麼使用 RegexObject
作第一個參數,或用使用模式內嵌修正器,如 sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'。