在python中用正则表达式替换字符串

时间:2013-11-19 21:21:35

标签: python regex string

我一直在学习正则表达式,但有时候仍然会感到困惑 我想替换所有的

self.assertRaisesRegexp(SomeError,'somestring'):

self.assertRaiseRegexp(SomeError,somemethod('somestring'))

我该怎么办?我假设第一步是获取'somestring'并将其修改为somemethod('somestring')然后替换原来的'somestring'

2 个答案:

答案 0 :(得分:0)

这个特定任务的更好工具是sed:

$ sed -i 's/\(self.assertRaisesRegexp\)(\(.*\),\(.*\))/\1(\2,somemethod(\3))/' *.py

sed将负责文件I / O,重命名文件等。

如果你已经知道如何进行文件操作,并迭代每个文件中的行,那么python re.sub行将如下所示:

new_line = re.sub(r"(self.assertRaisesRegexp)\((.*),(.*)\)", 
                  r"\1(\2,somemethod(\3)", 
                  old_line)

答案 1 :(得分:0)

这是你的正则表达式

#f is going to be your file in string form
re.sub(r'(?m)self\.assertRaisesRegexp\((.+?),((?P<quote>[\'"]).*?(?P=quote))\)',r'self.assertRaisesRegexp(\1,somemethod(\2))',f)

这会抓住匹配的东西并相应地替换它。它还可以通过在quote

中设置引用来确保引号正确排列

这里也没有必要迭代文件,第一个语句“(?m)”将它置于多行模式,因此它将正则表达式映射到文件中的每一行。我测试了这个表达式,它按预期工作!

测试

>>> print f
this is some
multi line example that self.assertRaisesRegexp(SomeError,'somestring'):
and so on. there self.assertRaisesRegexp(SomeError,'somestring'): will be many
of these in the file and I am just ranting for example
here is the last one self.assertRaisesRegexp(SomeError,'somestring'): okay 
im done now
>>> print re.sub(r'(?m)self\.assertRaisesRegexp\((.+?),((?P<quote>[\'"]).*?(?P=quote))\)',r'self.assertRaisesRegexp(\1,somemethod(\2))',f)
this is some
multi line example that self.assertRaisesRegexp(SomeError,somemethod('somestring')):
and so on. there self.assertRaisesRegexp(SomeError,somemethod('somestring')): will be many
of these in the file and I am just ranting for example
here is the last one self.assertRaisesRegexp(SomeError,somemethod('somestring')): okay 
im done now