Emacs regexp count occurrences

Viewed 9127

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
7 Answers

Here is a emacs-lisp function that does not use a stack

(defun count-occurences-in-string (pattern string)
  "Count occurences of PATTERN in STRING."
  (let ((occurences 0)
        (start 0)
        (length (length string)))
    (while (and
            (< start length)
            (string-match pattern string start))
      (setq occurences (1+ occurences))
      (setq start (match-end 0)))
    occurences))

If you don't have any problems creating a copy of the variable, you can try

(- (length (split-string "Hello World" "o")) 1)
(- (length (split-string "aaabaaa" "a")) 1)
(- (length (split-string "This
string
has three
newlines" "
")) 1)
2
6
3

If you don't have any problem loading the cl-lib package, then you can try

(require 'cl-lib)

(cl-count ?o "Hello World")
(cl-count ?a "aaabaaa")
(cl-count ?
 "This
string
has three
newlines")
2
6
3

I would probably do this:

(defun count-occurrences (regexp string)
  "Return the number of occurrences of REGEXP in STRING."
  (let ((count 0))
    (with-temp-buffer
      (save-excursion (insert string))
      (while (re-search-forward regexp nil t)
        (cl-incf count)))
    count))
Related