Sunday, August 11, 2013

Re: vim: how to use back reference to compare strings?

thanks again John!

I tried your 1st amendment , which is:
:g#\(abc\d\+\)\(.*\)\(abc\d\+\)\(.*\)#s//\=Diff(submatch(1),submatch(3))/n

really wireld , I still got the same result -- a message saying: "5 substitutions in 5 lines", nothing got "echo"ed out...
I copied from your email and pasted into my vim, are you sure it works in your vim ?

your second solution definitely works fine.
but, it doesn't look "simpler" to me (vimL beginner level) at all... I could understand the 1st oneliner better than this function -- I hope I can understand it though.



On Sun, Aug 11, 2013 at 3:08 AM, John Little <John.B.Little@gmail.com> wrote:
On Sunday, August 11, 2013 2:44:28 PM UTC+12, ping wrote:
> any idea of what I missed here?

With

:g#\(abc\d\+\)\(.*\)\(abc\d\+\)\(.*\)#s//\=Diff(submatch(1),submatch(2))/n

I get all lines reporting a difference, changing the echo to

   echo "found a diff!" a:a a:b

shows me why.

Back references are numbered from the left, by their opening \(.  Your pattern is

   \(abc\d\+\)\(.*\)\(abc\d\+\)\(.*\)

where you've bracketed the middle bit, so that's returned by submatch(2); you want to compare matches 1 and 3. Using

:g#\(abc\d\+\)\(.*\)\(abc\d\+\)\(.*\)#s//\=Diff(submatch(1),submatch(3))/n

I get

found a diff! abc123 abc1234
found a diff! abc123 abc1234
5 substitutions on 5 lines

It's an ugly hack, any way.  I've just noticed that the matchlist() function gives access to submatches, a function using that would be cleaner:

func! Diff2(pat)
    call setpos('.',[0, 1, 1, 0]) " go to beginning
    while search(a:pat, 'W')
        let l = matchlist(getline('.'),a:pat)
        if len(l) >= 4 && l[1] != l[3]
            echo 'found a diff:' l[1] l[3]
        endif
    endwhile
endfunc

:call Diff2('\(abc\d\+\)\(.*\)\(abc\d\+\)\(.*\)')

Regards, John Little

--
--
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/groups/opt_out.



--
--
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/groups/opt_out.

No comments: