Sunday, December 6, 2020

Re: Matching words within X lines

On 2020-12-06 18:11, A. Wik wrote:
> I'm trying to match a couple (maybe more later) of words occurring
> within 3 lines of each other in any order. Is there a way to do
> this with a Vim regex?

The short answer is "yes", but the specifics depend on what you mean.
Can the words come in any order? Is this for just 2 words? Or more
than two words? If they're sets of words, does it count to find the
*same* word within N lines?

For two words in a fixed order (HI followed by BYE in the subsequent
3 lines), you can do something like

/\<HI\>\%(.*\n\)\{,2}.*\<BYE\>

where the "2" is the N-lines-minus-1

For HI and BYE withing 3 lines but the order might be reversed (BYE
then HI), it's likely easiest to do the same thing with the "or"
conjunction:

/\<HI\>\%(.*\n\)\{,2}.*\<BYE\>\|\<BYE\>\%(.*\n\)\{,2}.*\<HI\>

For arbitrary sets of words or patterns, followed by up to 3 lines,
such as HEY, HI, and BYE

/\<\%(HI\|HEY\|BYE\)\>\%(.*\_.\)\{,2}.*\<\%(HEY\|HI\|BYE\)\>

though that could find instances where the first and second words are
the same such as "HI...HI". If you want to make sure they are
different, you might use this monster

/\<\(HI\|HEY\|BYE\)\>\%(.*\_.\)\{,2}.*\<\%(\1\>\)\@!\%(HEY\|HI\|BYE\)\>

which uses the "the thing we captured as the first word can't match
at the point where we find the second word" "\@!" token.

They're ugly, but vim will at least let you do them.

-tim




--
--
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

---
You received this message because you are subscribed to the Google Groups "vim_use" group.
To unsubscribe from this group and stop receiving emails from it, send an email to vim_use+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/vim_use/20201206202305.6067db6c%40bigbox.attlocal.net.

No comments: