我正在寻找最快的例程(不是交互式)来获取字符串中正则表达式的匹配数.
就像是
(count-occurrences "a" "alabama")
=> 4
Run Code Online (Sandbox Code Playgroud)
eve*_*_jr 11
how-many(别名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))
Run Code Online (Sandbox Code Playgroud)
这是一个使用递归和累加器的更实用的答案.作为额外的好处,它不使用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))
Run Code Online (Sandbox Code Playgroud)