Saturday, July 25, 2020

Re: How can I find where one word is close to another word?

On 2020-07-25 15:59, Adrian Keister wrote:
> Now is the time for all good men to come to the aid of their
> country.
>
> In this test, I want to find all occurrences where the word 'aid'
> is within ten words of the word 'country'. How can I do that in Vim?

It's way ugly and requires using the old regex engine[1] (asserted by
the "\%#=1" in the following pattern) to work, but this should do the
trick and be fairly DRY (only requires putting in each term once):

\%#=1\%(\S\+\_s\+\)\{,9}\<aid\>\&\%(\S\+\_s\+\)\{,9}\<country\>

I might have a fenceposting issue where "9" should be "8" or "10",
but it should give you the foundation to mess around. Also, I added
the "\<" and "\>" to anchor the words so you don't find things like
"I said my uncle is a country boy" (finding the "aid" in "said").
Again, season to taste for your own needs.

The cursor lands a little weirdly (especially noticable if you have
syntax highlighting turned on) because it starts from the point at
which "within the next N words you'll find "aid" and within the next N
words you'll also find "country".

Alternatively, if you don't mind typing your literals more than once,
you can do

/\<aid\>\%(\_s\+\S\+\)\{,10}\_s\+\<country\>\|\<country\>\%(\_s\+\S\+\)\{,10}\_s\+\<aid\>

which will highlight a little more neatly at the cost of extra typing.
However, it also doesn't scale as well if you have more than 2 words
because you need to provide every possible ordering. The method at
the top scales easily for however many words you want within an
N-word range.

Hopefully one or the other works well for you.

-tim


[1] For the record, the new regex engine gives me an

E363: pattern uses more memory than 'maxmempattern'

where the old engine works fine.




--
--
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/20200725184223.312a64f2%40bigbox.attlocal.net.

No comments: