VIM 替换部分模式

VIM replace in part of pattern

我想在部分模式中用引号内的下划线替换空格。

示例输入:

select 
    "AA" as "Long descriptive name",
    "BB" as "Another long name",
    "CC" as "There are many spaces here"
from 
    sometable;

想要的输出:

select 
    "AA" as "Long_descriptive_name",
    "BB" as "Another_long_name",
    "CC" as "There_are_many_spaces_here"
from 
    sometable;

我试过像这样使用 substitute() 和 submatch() 函数来执行此操作,但我无法让它正常工作(\= 部分未被解释,替代命令被写入文件)。少了点东西。

:%s/ as "\(.*\)"/ as \=substitute(submatch(1),' ', '_', 'g')/g

嗯,你很接近:

:%s/ as "\zs\(.*\)\ze"/\=substitute(submatch(1),' ', '_', 'g')/g

\= 仅当字符串以它开头时才被解释为表达式。参见 :h sub-replace-special。您可以通过匹配要替换的部分来解决该问题(在我的示例中使用 \zs\ze)。

这当然并不总是有效。然后你将不得不在 \= 部分再次构建一个字符串。看起来像这样:

:%s/ as "\(.*\)"/\=' as "'.substitute(submatch(1),' ', '_', 'g').'"'/g