15

我正在寻找最快的例程(非交互式)来获取字符串中正则表达式的匹配数。

就像是

(count-occurrences "a" "alabama")
=> 4
4

7 回答 7

27

count-matches以交互方式进行。也许是一个开始寻找的好地方。

于 2012-08-07T14:34:31.890 回答
14

how-many(aliased count-matches) 这样做,但适用于缓冲区。

这是一个适用于字符串的方法:

(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))
于 2012-08-07T14:37:49.357 回答
8

这是使用递归和累加器的更实用的答案。作为一个额外的好处,它不使用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))
于 2012-08-07T15:01:18.623 回答
3

在 package s中,有 function s-count-matches

于 2016-12-07T12:40:08.360 回答
1

这是一个不使用堆栈的 emacs-lisp 函数

(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))
于 2021-12-08T14:52:20.160 回答
0

如果创建变量副本没有任何问题,可以尝试

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

如果您在加载包时没有任何问题cl-lib,那么您可以尝试

(require 'cl-lib)

(cl-count ?o "Hello World")
(cl-count ?a "aaabaaa")
(cl-count ?
 "This
string
has three
newlines")
2
6
3
于 2021-01-30T03:23:34.373 回答
0

我可能会这样做:

(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))
于 2021-12-08T21:09:19.260 回答