替换vim中除括号部分以外的所有字符串

时间:2017-08-09 04:39:19

标签: regex vim

我的文字如下。

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行)之间的差异,空格。

2 个答案:

答案 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