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?
Asked
Active
Viewed 164 times
2
Vivian De Smedt
- 16,336
- 3
- 18
- 37
Amarakon
- 261
- 2
- 7
-
1Does this solve your problem: Store the number of matches in VimScript function? – 3N4N Oct 02 '22 at 02:58
-
1Looking at your regex I believe it will only match once. Maybe you would like to get the length of the matching string? – Vivian De Smedt Oct 02 '22 at 04: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 02 '22 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 02 '22 at 20:21
1 Answers
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