0

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"))
.
Konrad
  • 17,740
  • 16
  • 106
  • 167
  • The `E488: Trailing characters` is because you have a `/2` in the replace part that should be `\2`. – Marth Sep 01 '17 at 21:04
  • 1
    This works on your examples but no doubt it will get more trickier than that once you have escaped double quotes.`%s/\v\(inputid \= \zs(".{-}")\ze\)/ns(&)` – Lieven Keersmaekers Sep 01 '17 at 21:04

2 Answers2

1

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
DJMcMayhem
  • 7,285
  • 4
  • 41
  • 61
1

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

%s/\(inputId\s*=\s*\)\("[^"]*"\)/\1ns(\2)/g
anubhava
  • 761,203
  • 64
  • 569
  • 643