如何在Vim中交互式搜索/替换正则表达式中从前向后切换?

whi*_*roi 5 vim

例如,我有一些文字:

    'y'     to substitute this match
    'l'     to substitute this match and then quit ("last")
    'n'     to skip this match
    <Esc>   to quit substituting
    'a'     to substitute this and all remaining matches {not in Vi}
    'q'     to quit substituting {not in Vi}
Run Code Online (Sandbox Code Playgroud)

通过:%s/substitute/sub/gc我可以交互式搜索/替换.如果我按'n'进入下一个匹配的模式,我怎么能撤消'n'?或向后搜索?

在通常的搜索模式中,/search_word我们可以跳过"n","N"是否有类似的替代 - :%s/substitute/sub/gc

Ken*_*ent 7

Mathias Bergert的答案就是诀窍,如果你只需要简单的单字替换,替换文本总是固定的.也许这对我们日常编辑的70%感到满意.如果您需要s/.../.../替代需求的力量,可能还不够.例如,替换部分中的多个单词替换,后向引用或函数表达式.

我能想到的是,先做一个:

:s/substitute/sub/c
Run Code Online (Sandbox Code Playgroud)

注意,没有% rangeg标志.

那你就是:

  • nN进行/向后搜索,
  • 如果您认为应该替换比赛,请按&,
  • 如果你犯了一些错误,请按 u

关键是,&重做最后的替换.

通过这种方式,你可以做更复杂的替换,这很简单,cw如:

  • s/f../&, / 在所有fxx单词后添加逗号(foo,far,fur ......)
  • s/\v(foo)(\d+)/\=submatch(1).(submatch(2)+1)/ 之后的增量数 foo
  • 等等...


Mat*_*ert 6

我个人更喜欢.命令而不是替换c标志,这增加了更多的灵活性.

做这样的事情:

/substitute<cr>
cwsub<esc>
Run Code Online (Sandbox Code Playgroud)

搜索"替换",然后cw(更改单词)到"sub"(<esc>退出插入模式)

现在你可以使用nN移动和dot .命令将"替换"替换为"sub".随着u你甚至可以撤消最后一个.