提取正则表达式的匹配?

时间:2011-12-15 14:02:44

标签: regex emacs elisp

我喜欢在没有周围文本的单独缓冲区中查看正则表达式的匹配列表。例如,我喜欢看到HTML文档中定义的所有类名。另外我喜欢看每场比赛的数量。这有没有emacs库?

例如,如果我有文字:

add related resources or links
always respect the original author" 

和正则表达式

"re."

我正在寻找比赛并计算

rel: 1
res: 2

请注意,rel来自“相关”,res来自“资源”和“尊重”

1 个答案:

答案 0 :(得分:5)

(defun my-re-counter (regexp)
  (interactive "sregexp: ")
  (let (matches)
    (goto-char (point-min))
    (while (re-search-forward regexp nil t)
      (let ((match (assoc (match-string 0) matches)))
        (if match
            (setcdr match (1+ (cdr match)))
          (push (cons (match-string 0) 1) matches))))

    (pop-to-buffer "*regexp counts*")
    (erase-buffer)
    (dolist (match matches)
      (insert (car match) ": " (int-to-string (cdr match)) "\n"))
    (goto-char (point-min))))