Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex / Vim: Matching everything except a pattern, where pattern is multi-line?

Tags:

regex

vim

Is there a way in Vim to perform a similar operation to

:v/PATTERN/d 

where PATTERN is a multi-line regex pattern? I'm sure there is a way to do this in script, but I am mainly curious as to if it is possible to do using only standard regex substitution or Vim commands, because at this point it is more academic than an actual need.

My example is the following:

asdf

begin
   blah
end

asdf

alsdfjasf

begin
   random stuff
end
...

I want to get the blocks of begin/end with the lines between them, but ignore everything outside of the blocks, ultimately ending up with

begin
   blah
end

begin
   random stuff
end
...

My thoughts were to do

:v/begin\_.\{-}end/d 

where everything didn't match that would be deleted or even copied to register, but obviously :v and :g only work on single lines.

Then, I started going down the path of running a substitute and substitute everything with empty string that DIDN'T match the begin\_.\{-}end pattern, but I cannot grasp how to achieve such using look-behinds or anything. The regex works perfectly fine when just searching, but I can't figure out how to tell the regex engine to find everything BUT that pattern. Any ideas?

like image 741
jlewis Avatar asked Dec 27 '22 06:12

jlewis


1 Answers

clear reg a

qaq

append begin...end to reg a

:g/begin/,/end/y A

open new tab

:tabnew

put reg a

"ap
like image 137
kev Avatar answered May 19 '23 00:05

kev