Number of instances of Emacs regexp count

I am looking for the fastest procedure (not interactively) to get the number of regular expression matches in a string.

Something like

(count-occurrences "a" "alabama") => 4 
+8
regex emacs
source share
4 answers

Here is a more functional answer using recursion and battery. 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)) 
+5
source share

count-matches does this interactively. Maybe a good place to start looking.

+19
source share

how-many (aliased count-matches ) does this, but works on buffers.

Here's what works with 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)) 
+9
source share

There is an s-count-matches function in package s .

+1
source share

All Articles