Emacs Lisp: Regular Expression

By Xah Lee. Date: . Last updated: .

Regex Functions

Regex Syntax

How to Test Regex in Emacs Lisp Code

One simple way to test regex is to create a file with the following content:

(re-search-forward "yourRegex")

big text to search here


(let ((case-fold-search nil))
  (re-search-forward "\\.jpg"))
;; cat.jpg

save the file as test.el, reopen it, so it opens in emacs lisp mode so you have syntax coloring.

Then, put your cursor to the right of the closing parenthesis, then Alt+x eval-last-sexpCtrl+x Ctrl+e】. If your regex matches, it'll move cursor to the last char of the matched text. If you get a lisp error saying search failed, then your regex didn't match. If you get a lisp syntax error, then you probably screwed up on the backslashs.

Newline Character and Tab

Inside elisp string, \t is TAB char (Unicode codepoint 9), and \n is newline. You can use [\t\n ]+ for sequence of {tab, newline, space}.

When a file is opened in Emacs, newline is always \n, regardless whether your file is from {Unix, Windows, Mac}. Do NOT manually do find replace on newline chars for changing file newline convention. [see Emacs: Newline Representations ^M ^J ^L]

Backslash in Emacs Lisp Regex String

Literal double quote.
Any of chars
"[\t\n ]+"
Sequence of {tab, newline, space}.
Literal square bracket with abc inside.
Literal parenthesis and text.
Capture pattern.
First captured pattern. Used in replacement.
Second captured pattern. Used in replacement.

Here's complex example, suppose you have this text:

<img src="cat.jpg" alt="my cat" width="795" height="183" />

When you call a command such as list-matching-lines , you can type the regex in the prompt. Example:

<img src="\([^"]+?\)"

But in lisp code, the same regex needs to have many backslash escapes, like this:

(re-search-forward "<img src=\"\\([^\"]+?\\)\"" )

(info "(elisp) Regular Expressions")

Use emacs to Convert Regex to Elisp Regex String

There is a easy way to get the backslashes right.

The elisp string regex syntax will be shown in minibuffer. (with all correct backslashes if needed)

elisp regex 2021-06-26 nbX78
Alt+x list-matching-lines , followed by Alt+x repeat-complex-command

Find Replace Text

Regex in Elisp Syntax: rx Package

There is a elisp package rx that uses lisp style syntax to represent regex syntax.

(require 'rx)

;; this
(rx (one-or-more blank) line-end)

;; returns this
;; "[[:blank:]]+$"

I do not recommend it. Because it's a middleman. Just learn and use raw regex directly.

Emacs Regular Expression

Regex in Emacs Lisp

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics


Lisp Data Structure


Lisp Symbol

Lisp Misc

Working with Elisp