Wizard
Wizard

Reputation: 22083

Combine multiple replace-regexp to a program

I am working on cleaning files with multiple regex-replacement

<<.*>>                  -> ""
\([[:alpha:]]\)\*       -> \1 ;; patters as pragram* to program
\*\([[:alpha:]]\)       -> \1 ;; patters as *program to program
\*/\([[:alpha:]]\)      -> \1
;;and so on

On every single file, I have to invoke replace-regexp various times.

How could combine these regex search?

Upvotes: 0

Views: 136

Answers (1)

xuchunyang
xuchunyang

Reputation: 949

To an extent, M-x whitespace-cleanup has similar requirements, that is, cleanup base on multiple conditions. It should be possible to use (emacs) Keyboard Macros, but I am not familiar with it. Once you have some knowledge in Emacs Lisp, you can solve the problem easily, for example, the following cleanups leading and trailing spaces, you can add your regexp and their replacement into my-cleanup-regexps:

(defvar my-cleanup-regexps
  '(("^ +" "")
    (" +$" ""))
  "A list of (REGEXP TO-STRING).")

(defun my-cleanup-replace-regexp (regexp to-string)
  "Replace REGEXP with TO-STRING in the whole buffer."
  (goto-char (point-min))
  (while (re-search-forward regexp nil t)
    (replace-match to-string)))

(defun my-cleanup ()
  "Cleanup the whole buffer according to `my-cleanup-regexps'."
  (interactive)
  (dolist (r my-cleanup-regexps)
    (apply #'my-cleanup-replace-regexp r)))

Upvotes: 1

Related Questions