zoukankan      html  css  js  c++  java
  • python类库31[正则表达式之sub]


    实例在python2.6中测试通过,对python3.1需要相应的修改。 

    将下面字符串中的目录替换为新的目录c:\test\2011 或c:\test\2012。

    Hello
    dir=c:\test\2010
    How are you!
     

    一 使用Regex Match Tester来测试,如下:

     

    二 代码示例 

    import re

    oldline 
    = 'dir=c:\\test\\2010'
    str1 
    = 'Hello\n' + oldline +'\nHow are you!'
    print str1
    print '------------------------------------'

    newline 
    = 'dir=c:\\test\\2011'

    reobj 
    = re.compile('^(dir=)(.*)$',re.M)  
    newStr1 
    = reobj.sub(newline, str1 )
    print newStr1
    print '------------------------------------'

    newdir 
    = 'c:\\test\\2011'
    def f(m):
      
    return m.group(1+ newdir  
    newNewStr1 
    = reobj.sub(f, str1 )
    print newNewStr1
    print '------------------------------------'

    三 运行结果

     

    四 解析

    1)使用re.compile来产生正则表达式对象reobj,且通过re.M来设置为多行匹配;
    2)调用reobj的sub方法,sub方法的原型为RegexObject.sub(repl,string[,count=0]),其中repl可以为字符串或函数,如果是字符串时,字符串中所有的\均被处理,例如\n表示新行,\r表示换行,\g<name> = \g<2> = \2表示前面匹配到的group(2),其他的没有特殊意义的如\j则保持原样;
    3)如果repl为函数时,此函数只有一个参数为matchobject;

    以上的问题中因为repl中有\2,所以必须使用函数来处理!

    完!

  • 相关阅读:
    JdbcTemplate增删改查案例
    顾问和注解
    使用多种方式实现AOP
    面试题
    Spring Bean的生命周期和作用域
    IOC和AOP交互拓展(二)
    AOP
    错题
    Spring核心概念
    hadoop-MapReduce框架原理之OutputFormat数据输出
  • 原文地址:https://www.cnblogs.com/itech/p/2098885.html
Copyright © 2011-2022 走看看