如何在 vim 中执行搜索/替换,同时保留通配符内容?
这就是我的意思 -
假设我的文件中有这些,
ActiveRecord::Base.connection.execute("select * from table1").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table2").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table3").each_hash do ..
client.query("select * from table1").each_hash do ..
client.query("select * from table2").each_hash do ..
client.query("select * from table3").each_hash do ..
我只想仅用 each(:as => :hash)< 替换 ActiveRecord 的
each_hash
调用/code>,所以我会得到:
ActiveRecord::Base.connection.execute("select * from table1").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table2").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table3").each(:as => :hash) do ..
并使 client.query 行不受影响。
我知道我可以使用宏,但是如何使用 vim 的搜索/替换来做到这一点?我考虑过使用这个:
%s/\.execute(.*).each_hash/ ...something... /g
问题是,如何通过搜索和替换保留实际查询(...某物...所在的地方是什么)?
Here's what I mean -
Say I have these throughout my file
ActiveRecord::Base.connection.execute("select * from table1").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table2").each_hash do ..
ActiveRecord::Base.connection.execute("select * from table3").each_hash do ..
client.query("select * from table1").each_hash do ..
client.query("select * from table2").each_hash do ..
client.query("select * from table3").each_hash do ..
I want to replace only the ActiveRecord's each_hash
calls with each(:as => :hash)
, so I'd get:
ActiveRecord::Base.connection.execute("select * from table1").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table2").each(:as => :hash) do ..
ActiveRecord::Base.connection.execute("select * from table3").each(:as => :hash) do ..
And leave the client.query rows unaffected.
I know I can use macros, but how do I do this with vim's search/replace? I thought about using this:
%s/\.execute(.*).each_hash/ ...something... /g
The question is, how do I preserve the actual query through the search and replace (what comes where ...something... is)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
vim 正则表达式中
\zs
原子的完美用例。这告诉 vim 在进行替换时忽略\zs
之前(包括)的任何内容。关于
\zs
的更好解释可以在:help /\zs
中找到。Perfect use case for the
\zs
atom in vim's regex. This tells vim to ignore anything before (and including)\zs
when doing a replacement.A better explaination of
\zs
can be found at:help /\zs
.您可以使用
global
命令进行过滤。输入
:help :g
获取帮助:You can use the
global
command to filter.Type
:help :g
to get help:执行此操作的正则表达式:
请参阅
^\(\(.*client.*\)\@!.\)*
部分的说明:https://vim.fandom.com/wiki/Search_for_lines_not_containing_pattern_and_other_helpful_searchesA regex to do that:
See explanation for
^\(\(.*client.*\)\@!.\)*
part at: https://vim.fandom.com/wiki/Search_for_lines_not_containing_pattern_and_other_helpful_searches