I'm trying to count the number of regex matches in a line, and I need to use the result in a vim function. For example, count the number of open braces.
function! numberOfMatchesExample(lnum)
let line_text = getline(a:lnum)
" This next line is wrong and is the part I'm looking for help with
let match_list = matchlist(line_text, '{')
return len(match_list)
endfunction
So I'd like to find a way in a vim function to capture into a variable the number of regex matches of a line.
There are plenty of examples of how to do this and show the result on the status bar, see
:h count-items
, but I need to capture the number into a variable for use in a function.
The split()
function splits a string on a regular expression. You can use it to split the line in question, and then subtract 1 from the number of resulting pieces to obtain the match count.
let nmatches = len(split(getline(a:lnum), '{', 1)) - 1
See :h split()
.
For the special case of counting a single ASCII character like {
, I'd simply substitute()
away all other characters, and use the length:
:let cnt = len(substitute(line_text, '[^{]', '', 'g'))
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