代码之家  ›  专栏  ›  技术社区  ›  yPhil Erdogan Oksuz

Emacs正则表达式计数出现次数

  •  16
  • yPhil Erdogan Oksuz  · 技术社区  · 12 年前

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

    有点像

    (count-occurrences "a" "alabama")
    => 4
    
    7 回复  |  直到 12 年前
        1
  •  27
  •   Nicolas Dudebout    12 年前

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

        2
  •  14
  •   event_jr    12 年前

    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))
    
        3
  •  8
  •   event_jr    12 年前

    下面是一个使用递归和累加器的更实用的答案。作为额外的好处,它不使用 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))
    
        4
  •  4
  •   jco    8 年前

    在包装中 s ,有功能 s-count-matches

        5
  •  1
  •   cjohansson    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))
    
        6
  •  0
  •   doltes    4 年前

    如果您在创建变量副本时没有遇到任何问题,可以尝试

    (- (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.
    
        7
  •  0
  •   phils    3 年前

    我可能会这样做:

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