2

In Vim Script, I want to check for the amount of matches from a regular expression (/\%^\n*) and store the amount of matches in a variable. I this possible?

Vivian De Smedt
  • 16,336
  • 3
  • 18
  • 37
Amarakon
  • 261
  • 2
  • 7

1 Answers1

1

We can get the count of matches with :h searchcount(). It returns a dictionary with the following values:

key           type            meaning ~
current       |Number|        current position of match;
                              0 if the cursor position is
                              before the first match
exact_match   |Boolean|       1 if "current" is matched on
                              "pos", otherwise 0
total         |Number|        total count of matches found
incomplete    |Number|        0: search was fully completed
                              1: recomputing was timed out
                              2: max count exceeded

Since we only need the total match count, we can discard all values except total from the returned dictionary.

And as input searchcount takes a dictionary as its {options} parameter, which accepts a pattern. We can utilize this input parameter.

:let var = searchcount(#{pattern: '^\n'}).total
:echo var

NOTE: The hash character (#) before the dictionary argument of searchcount is a way to circumvent the requirement of quoting the dictionary keys; see :h literal-Dict.

3N4N
  • 5,684
  • 18
  • 45