Matthew
Matthew

Reputation: 6609

vim scripting - count number of matches on a line

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.

Upvotes: 4

Views: 1283

Answers (3)

glts
glts

Reputation: 22724

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

Upvotes: 5

Ingo Karkat
Ingo Karkat

Reputation: 172648

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'))

Upvotes: 3

ZyX
ZyX

Reputation: 53644

You can use a hack with substitute() with side effects:

function CountFigureBrackets(lnum)
    let line=getline(a:lnum)
    let d={'num': 0}
    call substitute(line, '{', '\=extend(d, {"num": d.num+1}).num', 'g')
    return d.num
endfunction

Upvotes: 2

Related Questions