Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs regexp count occurrences

Tags:

regex

emacs

I'm looking for the fastest routine (not interactively) to get the number of matches of a regexp in a string.

Something like

(count-occurrences "a" "alabama")
=> 4
like image 479
yPhil Avatar asked Aug 07 '12 13:08

yPhil


2 Answers

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

like image 94
Nicolas Dudebout Avatar answered Oct 02 '22 08:10

Nicolas Dudebout


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))
like image 35
event_jr Avatar answered Oct 02 '22 09:10

event_jr