Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vimscript: get all matches of a regex over a string

Tags:

regex

vim

In vimscript, we have substitute function which will accept flag 'g' to substitute all occurrences.

Is there a way to get all the matches strings?

For example, with string 'x y z', we can use substitute('x y z', '[a-z]', 'abc', 'g') to change it into abc abc abc.

However, is there any way to get the individual characters ['x', 'y', 'z']?

I know we can use match() to get the matched position, and matchstr() to get the matched string. But if I want to iterate through all matches, I have to call both functions which I think is not the efficient way.

So Is there any efficient way for getting all matches of a string in vimscript?

like image 694
LotAbout Avatar asked Dec 03 '15 02:12

LotAbout


1 Answers

You can use a substitute with a sub-replace-expression to capture all the matches.

let str = 'a b c'
let lst = []
call substitute(str, '[a-z]', '\=add(lst, submatch(0))', 'g')

For more help see:

:h sub-replace-expression
:h substitute
:h add()
:h submatch()
like image 185
Peter Rincker Avatar answered Sep 24 '22 03:09

Peter Rincker