Emacs: Quoting Regex in Emacs Lisp Code vs Command Prompt
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"
.
Backslash is escapte character.
"\n"
means newline, "\t"
means a tab character, and "\\"
means a literal single backslash.
When calling a emacs command that prompt for a regular expression, do not type the "string delimiters", nor adding extra backslash, because emacs auto convert your input to string.
But because it is not a string, it does not understand string syntax such as \n
or \t
.
You must use a literal newline or tab. [see Emacs: How to Insert a Tab Character or Newline].
For example, in emacs lisp, regex for matching a literal dot is "\\."
, but in a interactive call, you type \.
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