问题描述
是否可以做在vim中搜索和替换保留搜索词的大小写?这是我想念的一个有用的功能。
Is it possible to do a search and replace in vim that preserves the case of the search term? This was a useful feature in intelliJ that I miss.
例如:
:s/[uU]ser/[pP]erson/ (obviously, this doesn't work)
这样:
user->person
User->Person
保留多个字符的另一个例子:
Another example with multiple characters to preserve:
:s/[mM]y[uU]ser/[tT]his[pP]erson/g
这样:
myuser->thisperson
myUser->thisPerson
MyUser->ThisPerson
推荐答案
那里是一些可以采取的方法。如果你想坚持基本的Vim功能,你可以做类似的事情
There are a few approaches that can be taken. If you want to stick with basic Vim functionality, you can do something like
:%s/[uU]ser/\=submatch(0) ==# 'user' ? 'person' : 'Person'/g
如果您使用Perl绑定构建Vim,您可以制作使用:perldo
。根据匹配/替换单词的长度以及您要保留的案例的位置,这可能有效,也可能无效。
If you have Vim built with Perl bindings, you can make use of :perldo
. Depending on the length of the matching/replacing words and where the case you want to preserve is, this may or may not work.
:perldo s/(user)/"\L$1" ^ $1 ^ 'person'/ieg
或者您可以使用其中一个 实现此类功能。
Or you can make use of one of the various scripts that implement such functionality.
这篇关于VIM:如何保留搜索和替换的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!