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

问题描述 投票:0回答:3

我有一段文字如下。

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行),空格。

regex vim
3个回答
5
投票

您可以使用非贪婪的

.\{-}
匹配尽可能少的字符,然后可选地匹配带括号的组,然后匹配行尾:

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

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

0
投票

您还可以使用正则表达式:

:%s/^.\(.*(\d\)\@!.*\|^.\{-}\(..*(\d\)\@!/[[&]]
© www.soinside.com 2019 - 2024. All rights reserved.