search for brackets and add \ to it in gvim

Viewed 137

I am new to Vim. Please help to search and add \ to the string.

For example, for [1][sometest & numbers][7], the output should be [1]\[sometest & numbers\][7].

I could change the open bracket, [, with this

:%s/\[[a-z]\&\[/\\\[/g

but couldn't do it for ] (close bracket).

2 Answers

To match any ] or [ that are not part of a [<DIGITS_HERE>] substring, you may use

:%s/\v\[(\d+])@!|(\[\d+)@<!]/\\&/g

Here,

  • \v - truns on very magic mode
  • \[(\d+])@! - a [ char not followed with 1+ digits and then ]
  • | - or
  • (\[\d+)@<!] - a ] char not immediately preceded with [ and 1+ digits
  • /\\& - replacing the matches with \ and the found match
  • /g - globally.

Well the basic idea here is to split the string up into parts:

[1][sometest & numbers][7]

can be split into:

  1. [1]
  2. [
  3. sometest & numbers
  4. ]
  5. [7]

Then you build your string back with part 1 + \[ + part 3 + \] + part 5.

This can be done with capturing groups. have a look at :h \(. This should point you in the right direction. Have fun!

Related