在 vim 中使用 substitute 包围一组特殊字符

Surrounding one group with special characters in using substitute in vim

给定的字符串:

 some_function(inputId = "select_something"),
 (...)
 some_other_function(inputId = "some_other_label")

我想到达:

 some_function(inputId = ns("select_something")),
 (...)
 some_other_function(inputId = ns("some_other_label"))

这里的关键变化是元素 ns( ... ),它包围了 inputId[=24= 之后的 "" 中可用的字符串]

正则表达式

到目前为止,我想出了这个正则表达式:

:%substitute/\(inputId\s=\s\)\(\"[a-zA-Z]"\)/ns(/2/cgI

但是,在部署时,它会产生错误:

E488: Trailing characters

该正则表达式的更简单版本有效,语法:

:%substitute/\(inputId\s=\s\)/ns(/cgI

会在找到 inputId = 并创建字符串

后正确插入 ns(

some_other_function(inputId = ns("some_other_label")

挑战

我正在努力匹配字符串的剩余部分,例如。 "select_something") 和 return 为:

"select_something"))
.

你的正则表达式有很多问题。

  1. [a-zA-Z] 只会匹配一个字母。大概你想匹配下一个 " 之前的所有内容,所以你需要一个 \+ 并且你还需要匹配下划线。我会推荐 \w\+。除非超过 [a-zA-Z_] 可能在字符串中,在这种情况下我会做 .\{-}.

  2. 您有 /2 而不是 </code>。这就是为什么你得到 <strong>E488</strong>.</p></li> </ol> <p>我会这样做:</p> <pre><code>:%s/\(inputId = \)\(".\{-}\)"/ns()/cgI

    或使用开始匹配原子:(即\zs

    :%s/inputId = \zs\".\{-}"/ns(&)/cgI
    

您可以使用否定字符 class "[^"]*" 来匹配带引号的字符串:

%s/\(inputId\s*=\s*\)\("[^"]*"\)/ns()/g