繁体   English   中英

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

[英]replace a string with regular expression in python

我学习正则表达式已有一段时间了,但有时仍然感到困惑,有时我试图替换所有

self.assertRaisesRegexp(SomeError,'somestring'):

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

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

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)

这是你的正则表达式

#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设置引用,还可以确保引号正确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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM