LoginSignup
10
8

More than 5 years have passed since last update.

Emacs Lisp の正規表現、$ と \' の違い

Posted at

よく忘れるのでメモ。

正規表現で文字列の末尾を表現するときには $ を使いますよね。
Emacs Lisp ではもう一つの記述方法として \\' があります。

たとえば Emacs でファイルを開くときに特定のメジャーモードを設定したいとき、
変数 auto-mode-alist にファイル名のパターンとメジャーモードをセットします。
拡張子を指定するときは .html$ とか .txt$ とか $ で終わる正規表現を書きそうなものですが
デフォルトの定義は \\' を使っています。

files.el
(defvar auto-mode-alist
  ;; Note: The entries for the modes defined in cc-mode.el (c-mode,
  ;; c++-mode, java-mode and more) are added through autoload
  ;; directives in that file.  That way is discouraged since it
  ;; spreads out the definition of the initial value.
  (mapcar
   (lambda (elt)
     (cons (purecopy (car elt)) (cdr elt)))
   `(;; do this first, so that .html.pl is Polish html, not Perl
     ("\\.s?html?\\(\\.[a-zA-Z_]+\\)?\\'" . html-mode)
     ("\\.te?xt\\'" . text-mode)
     ("\\.[tT]e[xX]\\'" . tex-mode)
...

$ では動作しないのかというとそんなことはなく、きちんと拡張子にマッチします。

ではなぜ \\' を指定するのか。

\\' はバッファまたは文字列の末尾にマッチします。
一方、$ はバッファと文字列と行の末尾, つまり改行の直前にもマッチします。
複数行からなる文字列の末尾にマッチさせるときに m フラグ を指定する言語がありますが
Emacs Lisp の $m フラグ あり のときの動作になります。

拡張子はファイル名という改行を含まない文字列の末尾ですから \\' で十分なんですね。

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8