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?
1 Answer
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. Aug 1, 2015 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 throughregexp-quote
in thescratch
buffer orielm
. Aug 2, 2015 at 9:25