Delete anything other than pattern

前端 未结 3 1416
时光说笑
时光说笑 2020-12-30 04:50

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 ex

相关标签:
3条回答
  • 2020-12-30 05:28

    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.

    0 讨论(0)
  • 2020-12-30 05:38

    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
    
    0 讨论(0)
  • 2020-12-30 05:42

    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:

    • Create a function that count matches of a pattern in a string (see :help match() to help you design that)
    • Use: :%s/.*/\=repeat('text', matchcount('text', submatch(0)))
    0 讨论(0)
提交回复
热议问题