• 替换文件中字符(正则)


    替换文件中字符(正则)
    #!/usr/bin/env python

    import re

    filename = 'source.c'
    text = open(filename).read()

    r = re.compile(r'/*.*?*/', re.DOTALL)
    cr= re.compile('Copyright')

    def sub_copyright(m):
        mo = cr.search(m.group())
        if mo:
            return '/*xxx*/'
        else:
            return m.group()

    result = r.sub(sub_copyright, text)
    open('result.c', 'w').write(result)


    可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])

    replacement是被替换成的文本

    string是需要被替换的文本

    count是一个可选参数,指最大被替换的数量

    例子:

    import re
    p = re.compile(‘(blue|white|red)’)
    print(p.sub(‘colour’,'blue socks and red shoes’))
    print(p.sub(‘colour’,'blue socks and red shoes’, count=1))

    输出:

    colour socks and colour shoes
    colour socks and red shoes

    subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量

    例如:

    import re
    p = re.compile(‘(blue|white|red)’)
    print(p.subn(‘colour’,'blue socks and red shoes’))
    print(p.subn(‘colour’,'blue socks and red shoes’, count=1))

    输出

    (‘colour socks and colour shoes’, 2)
    (‘colour socks and red shoes’, 1)





  • 相关阅读:
    Oracle VM VirtualBox安装centos8
    HTML5 离线缓存manifest
    ES6 Proxy函数和对象的增强
    ES6 Map数据结构
    ES6 Set和WeakSet
    ES6Symbol在对象中的应用
    ==,===,与ES6中is()的区别
    ES6对象操作
    ES6函数和数组补漏
    ES6箭头函数
  • 原文地址:https://www.cnblogs.com/highroom/p/a920008110791660e2feb59427f2aa3b.html
Copyright © 2020-2023  润新知