Emacs: Regex Backslash in Emacs Lisp Code vs Command Prompt
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,
- In emacs command prompt, you type
\.
to match literal dot. One backslash to escape the meta meaning of the dot. - In emacs lisp code, regex for matching a literal dot is
"\\."
(extra backslash is used to escape the special meaning of backslash in string.)
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
"\n"
- Newline.
"\t"
- Tab.
"\""
- Literal double quote.
"[chars]"
- Any of chars
"[\t\n ]+"
- Sequence of {tab, newline, space}.
"\\[abc\\]"
- Literal square bracket with abc inside.
"(abc)"
- Literal parenthesis and text.
"\\(pattern\\)"
- Capture pattern.
"\\1"
- First captured pattern. Used in replacement.
"\\2"
- Second captured pattern. Used in replacement.
Example: Quoting Regex in Emacs Lisp Code
Here's example, suppose you have this text:
src="cat.jpg"
When you call a command such as
list-matching-lines
, you can type the regex in the prompt. Example:
src="\([^"]+?\)"
But in lisp code, the same regex needs to have many backslash escapes, like this:
(re-search-forward "src=\"\\([^\"]+?\\)\"" )
Emacs Regular Expression
- Regular Expression
- Regex Syntax
- About Quoting Regex
- Case Sensitivity
- How to Insert a Tab or Newline
- Wildcards vs Regex
- Emacs Regex vs Python, JavaScript, Java