Sunday, May 30, 2010

Re: Regex matching the first occurrence of a string

On May 28, 9:50 pm, ShayAllen <alexalle...@hotmail.com> wrote:
> I want to match everything between and including Begin and End. There are
> several blocks in the file:
>
> Begin
>   ssss
>   dfsdfsdf
>   sdfsdf
> End
>
> Begin
>   sasdfsa
>   sdfgsd
>   hghfgh
> End
>
> My best guess so far:
> :%s/Begin\_.*\(End\)\{-1}/This was one block/
> Doesn't work
>

One problem you have is that you use the "greedy" match, \_.*, so that
you will match everything between the FIRST begin and the LAST end.

Try using \_.\{-} instead, to match in a "non-greedy" fashion, so that
you only get the individual blocks.

From your title, I infer that you may want to match only the very
first block in the file. The easiest way to do this is probably just
to add the 'c' flag to the end of your substitute command, so that you
need to "confirm" each replacement (you could then cancel the
substitute after the first replacement).

So, your final command would be:

:%s/Begin\_.*\(End\)\{-1}/This was one block/c

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: