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

4

我有以下文本。

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)

有什么想法吗?

提前感谢您。

注意第4-5行中cat (1)zebra(1)之间的差异,即空格。

2个回答

5

您可以使用非贪婪模式的.\{-}匹配尽可能少的字符,然后可选地匹配一个括号分组,最后匹配行末:

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

你能解释一下 \@= 是什么意思吗? - plhn
@plhn:这是前瞻断言。它之前的\($\| (\)组被测试但不匹配。 - Ry-
非常感谢您的建议,但我不得不修改我的问题。它有一个错误 - plhn
@plhn:已更新。 - Ry-
@plhn:不,我只是想知道输入格式到底是什么。你想获取直到最后一个括号组,可选带一个空格的所有内容? - Ry-
显示剩余4条评论

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接