Vim视觉选择和正则表达式

7

我在视觉选择和运行正则表达式替换时遇到了问题。当我选择一些不包含整行的文本,然后按 : 弹出命令行, 运行以下命令:

:s/T/t/

然后,行中的第一个匹配项(无论是否被选中)都会被更改。例如,我有以下文本:

Test Text here

当我在界面上选择了Text这个单词,并运行了上述替换操作之后,得到的结果如下:

test Text here

这不是我想要得到的结果。

有什么办法可以实现正确的结果吗?

编辑:实际命令行是

'<,'>s/T/t/

当您在可视选择模式下按:键时,Vim会默认执行以下操作。

1个回答

16

您可以使用\%V(请参见http://vimdoc.sourceforge.net/htmldoc/pattern.html#//%V)。

\%V   Match inside the Visual area.  When Visual mode has already been
    stopped match in the area that |gv| would reselect.
    This is a |/zero-width| match.  To make sure the whole pattern is
    inside the Visual area put it at the start and end of the pattern,
    e.g.:
        /\%Vfoo.*bar\%V
    Only works for the current buffer.
所以:
:s/\%VT/t/

如果您想替换多个匹配项,请添加 /g。
:s/\%VT/t/g

1
根据:h %V,如果您想确保模式在选择范围内,则应将整个搜索模式包装在\%V中。例如::s/\%Vlongpattern\%V/short/ - m0tive
@m0tive:我引用了那个文档。当模式为单个字符时,它是没有用的。 - sehe
你太快了,我跟不上了;-) - m0tive
谢谢。我的实际模式超过一个字符,所以学习 %V 正是我所需要的。 - Greg Reynolds

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接