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是字符串的话,其中的任何反斜杠转义字符,都会被处理的。
    即:
         :会被处理为对应的换行符;
         :会被处理为回车符;
        其他不能识别的转移字符,则只是被识别为普通的字符:
            比如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();
第五个参数:flags

原文地址:https://www.cnblogs.com/fmgao-technology/p/9039923.html