Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim scripting - count number of matches on a line

Tags:

vim

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.

like image 402
Matthew Avatar asked Dec 25 '22 17:12

Matthew


2 Answers

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().

like image 118
glts Avatar answered Dec 28 '22 17:12

glts


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'))
like image 26
Ingo Karkat Avatar answered Dec 28 '22 17:12

Ingo Karkat