Friday, June 26, 2015

Re: How get a list of substrings matching a pattern?

On Fri, Jun 26, 2015 at 11:33 AM, BPJ <bpj@melroch.se> wrote:
I have succeeded in writing a function which splits the contents of a visual selection on a pattern, reverses the resulting list, joins it together on a separator and puts the result back into the visual selection (Yes that's kind of basic, right?):

    fun! RevList(...)
        let reg_save=@@
        let pattern=!exists('a:1') ? '\s*,\s*' : a:1
        let sep=!exists('a:2') ? ', ' : a:2
        normal gvy
        let @@=join(reverse(split(@@,pattern)),sep)
        normal gvp
        let @@=reg_save
    endfun

What I want to do is to make this smart enough to not split on commas (or whatever) which are inside quotes, so how do I extract all substrings which match a pattern rather than split on a pattern, the equivalent of `my @list = $string =~ m/($pattern)/g` in Perl? (Hopefully a pattern like '\v%(%(\s*\,\s*)@!.)+' will match the non-quoted parts...)

     I think you want to split on any comma that is not preceded by unbalanced quotation marks.   If you have to deal correctly with single and double quotation marks, then I am not sure it can be done with regular expressions.  As a starting point, see the notslash variable in matchit.vim:  https://github.com/benjifisher/matchit.zip/blob/master/plugin/matchit.vim#L85 .  What you want is a lot more complicated.  I assume that escaped quotes, like '\"', inside other quotes, do not count.

     Maybe you can work with something like this (after removing the spaces, assuming \v):

( [^,] | " ( [^"] | notslash \\")* " | ' ( [^'] | notslash \\')* ' ){-} \zs \s*,\s*

-- 
HTH
Benji Fisher


--
--
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.
For more options, visit https://groups.google.com/d/optout.

No comments: