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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With