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.

up vote 8 down vote accepted

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 '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 8 '17 at 4:51

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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