I'm currently stuck on this problem. I want, in a vimscript, to replace a variable's brackets when they contain a certain pattern.

To say this differently, say I have a variable foo = "[content] bar" . My purpose is to replace [content] with an empty string, which means that after the substitution we'll get: foo = " bar".

The current solution I could find is:

let foo = substitute(foo, "\[\]", "") | let foo = substitute(foo, "content", "")

but couldn't manage to get it in one call.

Is there something I'm missing? Could this be done more easily?



You can do it like this:


this somewhat cryptic regexp means to replace everything from start of bracket [ followed by anything not a closing bracket [^]]* followed by the closing bracket ] by nothing.

Update Since you like to replace variable contents, let me show how to do that. Suppose you have a variable foo (:let foo="[content] bar"), then you can do:

let foo=substitute(foo, '\[[^]]*\]', '', 'g')

The echo '|'.foo.'|' returns | bar| (note the leading space).

Make sure, to use single quotation marks, for double quotation marks you need to double the backslashes, as is explained in the help at :h expr-quote

  • Thanks Christian for the answer, I thought of using the :substitute command and indeed your suggestion is correct. However, I need this in a function, and applied to the foo var. Any thoughts?
    – J. Doe
    Aug 21 '17 at 18:01
  • the regex is still the same. You would simply use something like this: let foo=substitute(foo, <regex>, '', 'g') Aug 21 '17 at 18:03
  • I just tried, that doesn't replace anything :'(
    – J. Doe
    Aug 21 '17 at 18:09
  • @J.Doe you replaced <regex> by '\[[^]]*\]' in the substitute() call right?
    – statox
    Aug 21 '17 at 18:14
  • @statox yes, that's what I did.
    – J. Doe
    Aug 21 '17 at 18:16

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.