Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vimscript regex: write multiple matches in array

Tags:

regex

vim

I wrote a regex for vim which should find filenames. it looks like that:

let fileMatch = '\([-_a-zA-Z0-9]\+\.\)\+[a-zA-Z0-9]\+'
let fileName = matchstr(
    \ a:input_line,
    \ fileMatch
    \ )

Let's assume, that a:input_line has the value of:

(test/the/plugins.vim:13:2) (test/the/pluginsies.vim:13:2)

My goal is to have plugins.vim and pluginsies.vim in an array. I will work through that array afterwords.

Now if I echo fileName, I only get the first match: plugins.vim.

So, how can I save multiple matches in an array?

final solution

let fileMatch = '\([-_a-zA-Z0-9]\+\.\)\+[a-zA-Z0-9]\+'
let fileName = matchstr(
    \ a:input_line,
    \ fileMatch
    \ )
let result_list = map(split(a:input_line, fileMatch . '\zs'),'matchstr(v:val, fileMatch)')
like image 275
divramod Avatar asked Jan 19 '26 12:01

divramod


1 Answers

matchstr() will only return the first match. You can use loop to get all matched strings.

I noticed that you will ignore the filenames with spaces. so this one-liner may help to get all matched strings in a list:

let result_list = map(split(a:input_line),'matchstr(v:val, fileMatch)')

It will return:

['plugins.vim', 'pluginsies.vim'] 
like image 91
Kent Avatar answered Jan 21 '26 03:01

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!