我有一段文字如下。
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行),空格。
您可以使用非贪婪的
.\{-}
匹配尽可能少的字符,然后可选地匹配带括号的组,然后匹配行尾:
:%s/\(.\{-}\)\( \?([^)]*)\)\?$/[[\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
您还可以使用正则表达式:
:%s/^.\(.*(\d\)\@!.*\|^.\{-}\(..*(\d\)\@!/[[&]]