kdb
kdb

Reputation: 4416

String matching in emacs lisp matching arbitary string

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 \(, \)).

  1. Is the some function in emacs lisp, that is similiar to string-match-p but doesn't interpret regular expression syntax?
  2. As regexp-matching is implemented in C I assume that matching the correct regexp is faster than some 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

Answers (3)

user797257
user797257

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

sds
sds

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

Trey Jackson
Trey Jackson

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

Related Questions