re.sub(pattern, repl, string, count=0, flags=0)
这是它的原型,网上对此式解说文章,多不胜数。对第二个参数,repl,上述用法,述者寥寥。
但其功能,是以第一个参数,pattern中第一个组中值,替换pattern所匹配的字串,其格式为\number,编号从1开始第应第1组,以此类推,功能与\g<number>相同,为简洁写法。
比如:
s = '2017-01-22'
s = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2-\3-\1', s)
print s # 01-22-2017
r'\g<0>'能匹配pattern所适配的字串,而r'\0'却不能,这是测试中发现其不同处。
若在patter中有\number写法,则是要匹配其中分组,如下写法:
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
print "replacedStr=", replacedStr; #crifanli
它匹配了inuptStr整个字串,此字串,被crifanli完整替换之。
网友评论