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?
Asked
Active
Viewed 1,566 times
1 Answers
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.
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
. – dodgethesteamroller Aug 02 '15 at 09:25