9

I want to write a function (or use an existing one) that will take any string and produce a correctly escaped Regex that matches only that string. What is the fastest and simplest way of doing this?

PythonNut
  • 10,363
  • 2
  • 30
  • 76

1 Answers1

9

You are looking for 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.

This allows you to request an exact string match or search when calling a function that wants a regular expression.

Dan
  • 32,980
  • 7
  • 102
  • 169
  • I swear, I searched the docs and Google, I just didn't think of quote as a keyword. Thanks. – PythonNut Aug 01 '15 at 03:30
  • 1
    regexp-quote has the nice alternate use of escaping special characters in a string properly for use when a function expects a regexp in "Emacs form"--e.g. if you can't remember how many backslashes to use to escape a literal backslash, just run it through regexp-quote in the scratch buffer or ielm. – dodgethesteamroller Aug 02 '15 at 09:25