38

How to check if a string s1 is a substring of another string s2?

For example (test-substring "f t" "df tj") --> t, (test-substring "ft" "df tj") --> nil.

3 Answers 3

53

The standard Emacs Lisp approach is regular expression matching:

(string-match-p (regexp-quote needle) haystack)
0
26

cl-search can do that (and also returns the index of the substring, if found):

ELISP> (cl-search "f t" "df tj")
1 (#o1, #x1, ?\C-a)
ELISP> (cl-search "ft" "df tj")
nil
1
  • @Name, Has enough time passed?
    – tvaughan
    Aug 22, 2023 at 21:35
0

By the way, I also suggest string-match

(string-match REGEXP STRING &optional START) Probably introduced at or before Emacs version 17.

(string-match "12" "14 bla bla 12999") => 11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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