Skip to navigation

Emacs regular expressions: match at least n occurrences of character class

Aside: I just discovered the very useful Emacs regex builder tool. Type M-x regexp-builder.

I wanted a regular expression to match the pattern of mutt mail edit buffers, to apply mail-mode, but I did not want to match the muttrc and mutt.hooks files I have.

Mail edit buffers get a pattern that starts with “mutt”, followed by a combination of dashes, letters and numbers. Examples:


The pattern mutt[-0-9a-zA-Z]+$ matches these just fine, but it would also match muttrc. So I want a regex that looks for at least three occurrences from the character class described in the brackets. Generally, this is done using {3,} (using the {m,n} pattern to match at least m and at most n occurrences). (You can match exactly n occurrences, by using {3}).

In Emacs, this didn’t work, and it turns out I had to escape the curly brackets twice: mutt[-0-9a-zA-Z]\\{3,\\}$.

Here’s the full section in my .emacs file:

(defun mutt-edit-hook ()
  (setq fill-column 70)
  (setq make-backup-files nil)

(add-to-list 'auto-mode-alist '("mutt[-0-9a-zA-Z]\\{3,\\}$" . mail-mode))
(add-hook 'mail-mode-hook 'turn-on-auto-fill)
(add-hook 'mail-mode-hook 'mutt-edit-hook)

Comments are closed.