Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a substring of a string in Emacs Lisp?

Tags:

emacs

elisp

When I have a string like "Test.m", how can I get just the substring "Test" from that via elisp? I'm trying to use this in my .emacs file.

like image 426
Peter Avatar asked Sep 05 '12 04:09

Peter


2 Answers

One way is to use substring (or substring-no-properties):

(substring "Test.m" 0 -2) => "Test"

(substring STRING FROM &optional TO )

Return a new string whose contents are a substring of STRING. The returned string consists of the characters between index FROM (inclusive) and index TO (exclusive) of STRING. FROM and TO are zero-indexed: 0 means the first character of STRING. Negative values are counted from the end of STRING. If TO is nil, the substring runs to the end of STRING.

like image 169
dkim Avatar answered Sep 23 '22 01:09

dkim


Stefan's answer is idiomatic, when you just need a filename without extension. However, if you manipulate files and filepaths heavily in your code, i recommend installing Johan Andersson's f.el file and directory API, because it provides many functions absent in Emacs with a consistent API. Check out functions f-base and f-no-ext:

(f-base "~/doc/index.org") ; => "index"
(f-no-ext "~/doc/index.org") ; => "~/doc/index"

If, instead, you work with strings often, install Magnar Sveen's s.el for the same reasons. You might be interested in s-chop-suffix:

(s-chop-suffix ".org" "~/doc/index.org") ; => "~/doc/index"

For generic substring retrieval use dkim's answer.

like image 35
Mirzhan Irkegulov Avatar answered Sep 21 '22 01:09

Mirzhan Irkegulov