Let's say this is my text:
this is my text this
is my text this is my text
my text is this
I would like to highlight all text except pattern and delete the highlighted text.
p.e. text
: this must be the result.
text
texttext
text
I've found the code how to select all text except pattern:\%(\%(.{-}\)\@!text\zs\)*
however I don't know how to delete all highlighted text.
This doesn't work::%s/\%(\%(.{-}\)\@!bell\zs\)*//
Can anyone help me?
Try this:
:%s/\(^\|\(text\)\@<=\).\{-}\($\|text\)\@=//g
Explanation:
\(^\|\(text\)\@<=\) # means start of line, or some point preceded by “text”
.\{-} # as few characters as possible
\($\|text\)\@= # without globbing characters, checking that we reached either end of line or occurrence of “text”.
Another way to do it:
:help match()
to help you design that):%s/.*/\=repeat('text', matchcount('text', submatch(0)))
Forgive me, because I'm not a vim expert, but wouldn't prepending the search with v
find the inverse so that you could do something like this?
:v/pattern/d
I've implemented Benoit's clever regular expression as a custom :DeleteExcept
command in my PatternsOnText plugin. It offers other related commands like :SubstituteExcept
or :SubstituteInSearch
, too.
OP's example would be
:%DeleteExcept /text/
Comparing that with @Benoit's explicit command (:%s/\(^\|\(text\)\@<=\).\{-}\($\|text\)\@=//g
), it's a lot simpler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With