簡體   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