Test Regexp in Emacs

在 Emacs 中测试正则表达式是在和 Emacs Lisp 更近一层打交道的必经之路。 例如如下函数:

replace.el: replace-regexp
subr.el: replace-regexp-in-string
search.c: string-match, string-match-p
search.c: search-forward-regexp, search-backward-regexp
search.c: re-search-forward, re-search-backward

1. 可视化创建正则表达式: Re-builder

如同 re-builder.el 中的 commentary:

;; When I have to come up with regular expressions that are more
;; complex than simple string matchers, especially if they contain sub
;; expressions, I find myself spending quite some time in the
;; `development cycle’. `re-builder’ aims to shorten this time span
;; so I can get on with the more interesting bits.

;; With it you can have immediate visual feedback about how well the
;; regexp behaves to your expectations on the intended data.

在创建表达式过程中,可以通过渐进式的创建并及时得到当前 buffer 对测试正则的反馈,甚至不同颜色匹配不同的组/group 。 这样对于开发者来说,可以降低在正则这块的测试开发时间,将更多的时间放在其他开发内容上。

2. 自然语言思维创建正则表达式: rx

可能人更容易使用自然语言思维来创建正则表达式,有了 rx 这个宏:

(rx (or "foo" "bar" "baz"))
;;; equivalent to "\\(?:foo\\|bar\\|baz\\)"

如图使用 re-builder 来测试上述 rx 结果在本页面的验证结果: _20250712_201223screenshot.png