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).
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]
[
sometest & numbers
]
[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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.