Reputation: 4416
In emacs lisp I only know the functions string-match[-p]
, but I know no method for matching a literal string to a string.
E.g. assume that I have a string generated by some function and want to know if another string contains it. In many cases string-match-p
will work fine, but when the generated string contains regexp syntax, it will result in unexpected behaviour, maybe even crash if the regular expression syntax contained is invalid (e.g. unbalanced quoted parentheses \(
, \)
).
string-match-p
but doesn't interpret regular expression syntax?substring
/string=
loop; Is there some method to escape an arbitrary string into a regular expression that matches that string and only that string?Upvotes: 2
Views: 4103
Reputation:
Perhaps cl-mismatch
, an analogue to Common Lisp mismatch
function? Example usage below:
(mismatch "abcd" "abcde")
;; 4
(mismatch "abcd" "aabcd" :from-end t)
;; -1
(mismatch "abcd" "aabcd" :start2 1)
;; nil
Ah, sorry, I didn't understand the question the first time. If you want to know whether the string is a substring of another string (may start at any index in the searched string), then you could use cl-search
, again, an analogue of Common Lisp search
function.
(search "foo\\(bar" "---foo\\(bar")
;; 3
Upvotes: 0
Reputation: 60014
Either use regexp-quote
as recommended by @trey-jackson, or don't use strings at all.
Emacs is not optimized for string handling; it is optimized for buffers. So, if you manipulate text, you might find it faster to create a temporary buffer, insert your text there, and then use search-forward
to find your fixed string (non-regexp) in that buffer.
Upvotes: 4
Reputation: 74430
Are you looking for regexp-quote
?
The docs say:
(regexp-quote STRING)
Return a regexp string which matches exactly STRING and nothing else.
And I don't know that your assumption in #2 is correct, string=
should be faster...
Upvotes: 8