Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all strings except the parenthesis part in vim

Tags:

regex

vim

I have a text as follows.

cat
dog
elephant
cat (1)
zebra(1)
snow leopard
shark (other)
animal (hi) (2)

and I want to replace them as follows.

[[cat]]
[[dog]]
[[elephant]]
[[cat]] (1)
[[zebra]](1)
[[snow leopard]]
[[shark]] (other)
[[animal (hi)]] (2)

Any ideas?

Thank you for advance.

Note the difference between cat (1) and zebra(1)(line 4~5), the space.

like image 204
plhn Avatar asked Mar 09 '23 09:03

plhn


1 Answers

You could match as few characters as possible with a non-greedy .\{-}, then optionally match a parenthesized group, then match the end of the line:

:%s/\(.\{-}\)\( \?([^)]*)\)\?$/[[\1]]\2/
like image 64
Ry- Avatar answered Mar 15 '23 21:03

Ry-