Multi-line regex in Vim: filtering out blocks of text in a file

旧城冷巷雨未停 提交于 2020-01-05 07:07:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!