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?

4
  • 1
    Does this solve your problem: Store the number of matches in VimScript function?
    – 3N4N
    Oct 2, 2022 at 2:58
  • 1
    Looking at your regex I believe it will only match once. Maybe you would like to get the length of the matching string? Oct 2, 2022 at 4:47
  • You are right, it does only match once. What I actually intend to do is store the amount of leading blank lines (not including lines with only whitespace) into a variable.
    – Amarakon
    Oct 2, 2022 at 20:20
  • @kadekai the solutions posted there work with characters, but they do not seem to work with regular expressions (it returns the incorrect amount).
    – Amarakon
    Oct 2, 2022 at 20:21

1 Answer 1

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.