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.

1 Answer 1

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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