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?

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.

  • I swear, I searched the docs and Google, I just didn't think of quote as a keyword. Thanks. – PythonNut Aug 1 '15 at 3: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 2 '15 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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