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.


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

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

1 Answer 1


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\\$

  • 1
    Great, thanks! But why was this so difficult to find? Sometimes Emacs' documentation drives me crazy.
    – tmalsburg
    Jun 17, 2015 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, 2015 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 8, 2017 at 4:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.