实例在python2.6中测试通过,对python3.1需要相应的修改。
将下面字符串中的目录替换为新的目录c:\test\2011 或c:\test\2012。
Hello
dir=c:\test\2010
How are you!
一 使用Regex Match Tester来测试,如下:
二 代码示例
importre
oldline='dir=c:\\test\\2010'str1='Hello\n'+oldline+'\nHow are you!'printstr1print'------------------------------------'newline='dir=c:\\test\\2011'reobj=re.compile('^(dir=)(.*)$',re.M)
newStr1=reobj.sub(newline, str1 )printnewStr1print'------------------------------------'newdir='c:\\test\\2011'deff(m):returnm.group(1)+newdir
newNewStr1=reobj.sub(f, str1 )printnewNewStr1print'------------------------------------'
三 运行结果
四 解析
1)使用re.compile来产生正则表达式对象reobj,且通过re.M来设置为多行匹配;
2)调用reobj的sub方法,sub方法的原型为RegexObject.sub(repl,string[,count=0]),其中repl可以为字符串或函数,如果是字符串时,字符串中所有的\均被处理,例如\n表示新行,\r表示换行,\g = \g<2> = \2表示前面匹配到的group(2),其他的没有特殊意义的如\j则保持原样;
3)如果repl为函数时,此函数只有一个参数为matchobject;
以上的问题中因为repl中有\2,所以必须使用函数来处理!
完!