Surrounding one group with special characters in using substitute in vim

162 views Asked by At

Given string:

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

I would like to arrive at:

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

The key change here is the element ns( ... ) that surrounds the string available in the "" after the inputId

Regex

So far, I have came up with this regex:

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

However, when deployed, it produces an error:

E488: Trailing characters

A simpler version of that regex works, the syntax:

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

would correctly inser ns( after finding inputId = and create string

some_other_function(inputId = ns("some_other_label")

Challenge

I'm struggling to match the remaining part of the string, ex. "select_something") and return it as:

"select_something"))
.

2

There are 2 answers

0
DJMcMayhem On BEST ANSWER

You have many problems with your regex.

  1. [a-zA-Z] will only match one letter. Presumably you want to match everything up to the next ", so you'll need a \+ and you'll also need to match underscores too. I would recommend \w\+. Unless more than [a-zA-Z_] might be in the string, in which case I would do .\{-}.

  2. You have a /2 instead of \2. This is why you're getting E488.

I would do this:

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

Or use the start match atom: (that is, \zs)

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

You can use a negated character class "[^"]*" to match a quoted string:

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