问题
What is the correct regex for filtering multiple-lined blocks of text that end with #tags? My file looks like this:
Text block 1:
- something
- something
- something
#tag1 #tag2
Text block 2:
- somethingelse
- somethingelse
#tag2
Text block 3:
- really interesting stuff
- really interesting stuff
#tag1
etc
These great tips pointed me to using \_.. Hence, for filtering out both blocks containing #tag1, I came up with this:
\_.\{-}#tag1.*
That, however, only gives me Text block 1. Instead of pointing me further to Text block 2 (which also contains the tag), the cursor starts moving downwards line-by-line.
Where am I going wrong? Thanks for any explanations!
EDIT: A follow-up on how to create a multi-command for this kind of query is here.
回答1:
This works for me if you want to match every line in the block (use to yank all text in the matching blocks into a buffer)
^\(.\+\n\)\{-}#.*tag1
So you could do
g/^\(.\+\n\)\{-}#.*tag1/d A
To delete all text blocks(change d to y if you want to yank them instead, of course) that end with a #tag1 and yank them into register A, then "ap to paste them all (or <C-r>a in insert mode)
This lets me jump to the first line of each block that ends with tags containing tag1.
\(\%^\|^\n\)\zs.\(.\+\n\)\{-}#.*tag1.*$
The problem with
\_.\{-}#tag1.*
Is that while you're using {-} to be non-greedy, it's still always going to match as long as there is a line that has #tag1 below the current line that you're on. Using _.* or _.{-} can be pretty dangerous. For example when you are on the line "Text block 2:"
Text block 2:
- somethingelse
- somethingelse
#tag2
Text block 3:
- really interesting stuff
- really interesting stuff
#tag1
You get a match for the entire range Text block 2 until #tag1 after text block 3.
If instead you had
Text block 3:
- really interesting stuff
- really interesting stuff
#tag1
Text block 2:
- somethingelse
- somethingelse
#tag2
You would only match lines in Text block 3.
来源:https://stackoverflow.com/questions/10076834/multi-line-regex-in-vim-filtering-out-blocks-of-text-in-a-file