简体   繁体   English

Emacs 正则表达式计数出现

[英]Emacs regexp count occurrences

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

count-matches does it interactively. count-matches交互方式进行。 Maybe a good place to start looking.也许是一个开始寻找的好地方。

how-many (aliased count-matches ) does this, but works on buffers. how-many (别名为count-matches )执行此操作,但适用于缓冲区。

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

Here is a more functional answer using recursion and an accumulator.这是使用递归和累加器的更实用的答案。 As an added benefit, it does not use cl :作为一个额外的好处,它不使用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

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如果加载cl-lib包没有问题,那么你可以试试

(require 'cl-lib)

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

Here is a emacs-lisp function that does not use a stack这是一个不使用堆栈的 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))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM