在Vim中交互式搜索/替换正则表达式?

时间:2009-02-03 02:34:26

标签: regex vim

我知道正在进行全局替换的正则表达式,

     %s/old/new/g

如何在Vim中进行交互式搜索替换?

7 个答案:

答案 0 :(得分:414)

添加标志 c (在vim命令提示符下):

:%s/old/new/gc
每次出现'old'时,

会给你一个是/否提示。

"old" is highlighted in the text; at the bottom of the window it says "replace with new (y/n/a/q/l/^E/^y)?)"

一旦选择了确认替换,Vim的内置帮助就会提供有关可用选项的有用信息。使用:

:h :s

然后滚动到确认选项部分。屏幕截图如下:

Text that says "[C] Confirm each substitution. [...] CTRL-Y to scroll the screen down"

例如,要替换此匹配项和所有剩余匹配项,请使用a

答案 1 :(得分:73)

Mark Biek指出:

%s/old/new/gc

用于全局搜索替换每个替换的确认。但是,我也喜欢以交互方式验证旧文本是否正确匹配。我首先使用正则表达式进行搜索,然后重用该模式:

/old.pattern.to.match
%s//replacement/gc

s//将使用最后一种搜索模式。

答案 2 :(得分:19)

我认为您正在寻找c,例如s/abc/123/gc,这将导致VIM确认替换。请参阅:help:替换更多信息。

答案 3 :(得分:9)

我通常使用find / substitute / next / repeat命令: - )

/old<CR>3snew<ESC>n.n.n.n.n.n.n.

那是find "old"substitute 3 characters for "new"find nextrepeat substitute等。

这对于大规模替换是一种痛苦,但它可以让您有选择地忽略一些旧的替换(只需再次按n找到下一个而不是.重复替换)。

答案 4 :(得分:9)

如果您只想计算'abc'的出现次数,那么您可以%s/abc//gn。这不会取代任何东西,只会报告'abc'的出现次数。

答案 5 :(得分:3)

答案 6 :(得分:0)

Neovim现在具有预览替换的功能:

enter image description here

图片取自:https://medium.com/@eric.burel/stop-using-open-source-5cb19baca44d 功能文档:https://neovim.io/doc/user/options.html#'inccommand'