[英]Emacs regexp count occurrences
我正在尋找最快的例程(非交互式)來獲取字符串中正則表達式的匹配數。
就像是
(count-occurrences "a" "alabama")
=> 4
count-matches
交互方式進行。 也許是一個開始尋找的好地方。
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))
這是使用遞歸和累加器的更實用的答案。 作為一個額外的好處,它不使用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))
在包s 中,有函數s-count-matches
。
如果您在創建變量副本時沒有任何問題,您可以嘗試
(- (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
這是一個不使用堆棧的 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))
我可能會這樣做:
(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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.