我的文字如下。
cat
dog
elephant
cat (1)
zebra(1)
snow leopard
shark (other)
animal (hi) (2)
我想按照以下方式更换它们。
[[cat]]
[[dog]]
[[elephant]]
[[cat]] (1)
[[zebra]](1)
[[snow leopard]]
[[shark]] (other)
[[animal (hi)]] (2)
有什么想法吗?
感谢您提前。
注意 cat (1)
和zebra(1)
(第4~5行)之间的差异,空格。
答案 0 :(得分:5)
您可以使用非贪婪的:%s/\(.\{-}\)\( \?([^)]*)\)\?$/[[\1]]\2/
匹配尽可能少的字符,然后可选地匹配带括号的组,然后匹配该行的结尾:
ProxyPreserveHost On
答案 1 :(得分:2)
我的解决方案使用非常神奇的正则表达式:
/\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