re.sub()

python re
sub方法

re.sub(pattern, repl, string, count=0, flags=0)

re是regular expression的所寫,表示正則表達式
sub是substitute的所寫,表示替換;
re.sub是個正則表達式方面的函數,用來實現經過正則表達式,實現比普通字符串的replace更增強大的替換功能;

re.sub的含義,做用,功能:
對於輸入的一個字符串,利用正則表達式(的強大的字符串處理功能),去實現(相對複雜的)字符串替換處理,而後返回被替換後的字符串

re.sub的各個參數的詳細解釋
re.sub共有五個參數。
其中三個必選參數:pattern, repl, string
兩個可選參數:count, flags

第一個參數:pattern
    pattern,表示正則中的模式字符串,這個沒太多要解釋的
    i = re.sub(r'\s+', '', i)

第二個參數:repl
    repl,就是replacement,被替換,的字符串的意思。
    repl能夠是字符串,也能夠是函數
    若是repl是字符串的話,其中的任何反斜槓轉義字符,都會被處理的。
    即:
        \n:會被處理爲對應的換行符;
        \r:會被處理爲回車符;
        其餘不能識別的轉移字符,則只是被識別爲普通的字符:
            好比\j,會被處理爲j這個字母自己;
        反斜槓加g以及中括號內一個名字,即:\g<name>,對應着命了名的組,named group
    repl是函數    
    舉例說明:
    好比輸入內容是:
    hello 123 world 456
    想要把其中的數字部分,都加上111,變成:
    hello 234 world 567    
    
        import re;
        def pythonReSubDemo():
            """
                demo Pyton re.sub
            """
            inputStr = "hello 123 world 456";
            
            def _add111(matched):
                intStr = matched.group("number"); #123
                intValue = int(intStr);
                addedValue = intValue + 111; #234
                addedValueStr = str(addedValue);
                return addedValueStr;
                
            replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
            print "replacedStr=",replacedStr; #hello 234 world 567
        
        ###############################################################################
        if __name__=="__main__":
            pythonReSubDemo();
        
第三個參數:string

    string,即表示要被處理,要被替換的那個string字符串。
    沒什麼特殊要說明。        
第四個參數:count
    舉例說明:
    繼續以前的例子,假如對於匹配到的內容,只處理其中一部分。
    好比對於:
    hello 123 world 456 nihao 789
    只是像要處理前面兩個數字:123,456,分別給他們加111,而不處理789,        
        import re;
 
        def pythonReSubDemo():
            """
                demo Pyton re.sub
            """
            inputStr = "hello 123 world 456 nihao 789";
            
            def _add111(matched):
                intStr = matched.group("number"); #123
                intValue = int(intStr);
                addedValue = intValue + 111; #234
                addedValueStr = str(addedValue);
                return addedValueStr;
                
            replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr, 2);
            print "replacedStr=",replacedStr; #hello 234 world 567 nihao 789
        
        ###############################################################################
        if __name__=="__main__":
            pythonReSubDemo();
第五個參數:flagspython

相關文章
相關標籤/搜索