2

I try to do a substitution from a vim script and to operate over a captured group like so:

let string = "{b1} {b2} ({b3})"
echo substitute(string, "{\([^}]*\)}", "a", "g")

It doesn't match anything and the result doesn't change.

If I remove the \( \):

echo substitute(string, "{[^}]*}", "a", "g")

Then the whole {b1} is replaced with a, when I only want to replace the content of it: {a}.

I have read that the pattern in the substitute command always work in magic mode. And that in the magic mode, the capture group is: \( \).

Do you know the trick to make this work?

Edit: Thanks to Christian Brabandt I was able to make it work (see his answer below). I had to change the \( \) to \zs \ze also.

3

In double-quote strings, the backslash has a special meaning. And will probably be skipped when parsing the quoted string. The details can be seen at :h expr-quote. You would have to double the slashes to make that work.

Therefore, it is usually easier to read and maintain using single quoted strings. See :h literal-string as there the backslash won't be skipped.

  • Do you know a usecase where the expr-quote is a better use than a literal-string ? – nobe4 Sep 2 '15 at 9:37
  • When you need keys like in :exe ":norm! afoobar\<esc>" or when you need special chars e.g. \xe4 – Christian Brabandt Sep 2 '15 at 12:09
  • I see, meanwhile I found google.github.io/styleguide/vimscriptguide.xml where this is explained also :) – nobe4 Sep 2 '15 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.