Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate through regex results vimscript

Tags:

vim

In vimscript, how can I iterate through all the matches of a regex in the current file and then run a shell command for each result?

I think this is a start but I cant figure out how to feed it the whole file and get each match.

while search(ENTIRE_FILE, ".*{{\zs.*\ze}}", 'nw') > 0
    system(do something with THIS_MATCH)
endwhile
like image 821
kmulvey Avatar asked Nov 13 '22 19:11

kmulvey


1 Answers

Assuming that we have a file with the content:

123 a shouldmatch
456 b shouldmatch
111 c notmatch

And we like to match

123 a shouldmatch
456 b shouldmatch

with the regex

.*shouldmatch

If you only have one match per line you can use readfile() and afterwards loop through the lines and check each line with matchstr(). [1]

function! Test001()
  let file = readfile(expand("%:p")) " read current file
  for line in file
    let match = matchstr(line, '.*shouldmatch') " regex match
    if(!empty(match))
      echo match
      " your command with match
    endif
  endfor
endfunction

You can put this function in your ~/.vimrc and call it with call Test001().

[1] http://vimdoc.sourceforge.net/htmldoc/eval.html#matchstr%28%29

like image 116
jens-na Avatar answered Jan 04 '23 01:01

jens-na