Emacs: Regex Backslash in Emacs Lisp Code vs Command Prompt

By Xah Lee. Date: . Last updated: .

Regex in Emacs Lisp Code

In emacs lisp code, regular expression is a String, thus it follows string syntax. It needs to be enclosed by double quote string delimiters like "this".

In string, backslash is escape character. "\n" means newline, "\t" means a tab character, and "\\" means a literal single backslash.

Regex in Emacs Command's Prompt

In emacs command's prompt, regex is not a string. Do not type the the string quote.

But because it is not a string, it does not understand string syntax such as \n for newline. You must use a literal newline or tab. [see Emacs: How to Insert a Tab Char or Newline].

For example,

Newline Character and Tab in Lisp Regex String

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.

Example: Quoting Regex in Emacs Lisp Code

Here's example, suppose you have this text:


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


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

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

Regular Expressions (ELISP Manual)

Emacs Regular Expression

Regex in Emacs Lisp