Emacs regexp count occurrences
how-many
(aliased count-matches
) does this, but works on buffers.
Here is one that works on strings:
(defun how-many-str (regexp str)
(loop with start = 0
for count from 0
while (string-match regexp str start)
do (setq start (match-end 0))
finally return count))
Here is a more functional answer using recursion and an accumulator. As an added benefit, it does not use cl
:
(defun count-occurences (regex string)
(recursive-count regex string 0))
(defun recursive-count (regex string start)
(if (string-match regex string start)
(+ 1 (recursive-count regex string (match-end 0)))
0))
count-matches
does it interactively. Maybe a good place to start looking.