Replace all lines except the bracket in vim

I have the 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 your promotion.

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

+4
source share
2 answers

You can match as few characters as possible with non-living .\{-}, and then optionally match the group in brackets, and then match the end of the line:

:%s/\(.\{-}\)\( \?([^)]*)\)\?$/[[\1]]\2/
+5
source

My solution using a very magical regex:

/\v(^\w+(\s\w+)?)
:%s,,[[\1]],g

First the search
\v ......... stats very magic (avoiding lots of scapes)
( .......... starts group one
^ .......... beginning of line
\w+ ........ at least one word
( .......... starts group two inside group one (it will become optional at the end
\s ........  space
\w+ ........ another word 
) ........... closes groupo two
? ........... makes group two optional inside groupo one
) ........... closes group one
+2
source

Source: https://habr.com/ru/post/1683305/


All Articles