12

I'm composing a complex regular expression and the user can supply a part of the expression. However, the user-supplied part should be interpreted literally, i.e. regexp special characters should be escaped. Is there a function for escaping these characters? It seems like a common thing to do but all my googling was unsuccessful.

Example:

(re-search-forward (format "\b%s\b" user-string))

If user-string is test*case, I want to match test*case but not testttttcase.

tmalsburg
  • 2,540
  • 1
  • 14
  • 29

1 Answers1

17

You can use regexp-quote:

This function returns a regular expression whose only exact match is string. Using this regular expression in looking-at will succeed only if the next characters in the buffer are string; using it in a search function will succeed if the text being searched contains string.

(regexp-quote "^The cat$") => \\^The cat\\$

Dan
  • 32,584
  • 6
  • 98
  • 168
  • 1
    Great, thanks! But why was this so difficult to find? Sometimes Emacs' documentation drives me crazy. – tmalsburg Jun 17 '15 at 20:53
  • 2
    You can describe what you looked for, and where you expected to find about this function, with M-x report-emacs-bug. Perhaps the documentation is lacking and should be fixed. – YoungFrog Jun 17 '15 at 21:07
  • 2
    @tmalsburg A useful keyword would be "escape". Perhaps `(defalias 'regexp-escape 'regexp-quote)`. Was this discussed on any of the emacs mailing lists? – ebpa Mar 08 '17 at 04:51