by shigemk2

当面は技術的なことしか書かない

文字列の集合にマッチする正規表現を作成する

regexp-optを使い、文字列の集合にマッチする正規表現を作成する。
第二引数tを使うと、\(......\)でグルーピングされる。

;; prognがprog1にマッチする正規表現
(setq re (regexp-opt '("progn" "prog1") t)) ; => "\\(prog[1n]\\)"
(string-match re "progn")		  ; => 0
(string-match re "prog2")		  ; => nil
;; 他の正規表現と組み合わせる
(setq re (concat "<" (regexp-opt '("cat" "dog") t) ">")) ; => "<\\(cat\\|dog\\)>"
(and (string-match re "<cat>") (match-string 1 "<cat>")) ; => "cat"
(setq re (regexp-opt '("cat" "dog") 'words))		 ; => "\\(cat\\|dog\\)"
(string-match re "cat")					 ; => 0
(string-match re "concat")				 ; => 3
;; メタ文字はエスケープされる
(setq ops (regexp-opt '("+" "-" "*" "/" "1+") t)) ; => "\\(1\\+\\|[*+/-]\\)"
(string-match ops "1+3")			; => 0

P175

Emacs Lispテクニックバイブル

Emacs Lispテクニックバイブル