美文网首页
re.sub() 正则替换中关于分组的操作

re.sub() 正则替换中关于分组的操作

作者: 北游_ | 来源:发表于2018-08-31 16:31 被阅读202次

    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完整替换之。

    相关文章

      网友评论

          本文标题:re.sub() 正则替换中关于分组的操作

          本文链接:https://www.haomeiwen.com/subject/vmfewftx.html