Elisp: String Functions

By Xah Lee. Date: . Last updated: .

Here are the most basic string functions in elisp.

Length

;; length
(length "abc") ; returns 3

Substring

;; Extract a substring
(substring myStr myStartPos myEndPos)

Join Strings

;; join strings
(concat "some" "thing")

Match String by Regex

;; check if a string matches a pattern
(string-match myRegex myStr)

See also:

Get Captured String from Regex Match

In emacs, most functions that take a regex argument, after being called, will save/modify info in “match data”, such as caputured groups.

Match data can be accessed by the function match-data, and other functions.

The most useful is match-string, which returns the captured string.

;; get captured match
;; second argument is optional, but required if the last match is done by “string-match”
(match-string 1 myStr)

Replace in String

;; change a given string using regex. Returns changed string.
(replace-regexp-in-string myRegex myReplacement myStr)

Split String

;; split string into parts, returns a list
(split-string "xy_007_cat" "_")

String To/From Number

(string-to-number "3") ; change datatype
(number-to-string 3) ; convert to string
(format "%d" 3) ; similar to number-to-string but with fine control

Buffer Text to String

Elisp: Get Buffer String

String to Buffer

Emacs has only a few functions that takes a string as argument. Any non-trivial string processing is done with a buffer.

If you got a big string already somehow, you can put into a buffer by using with-temp-buffer, then insert your string, process it, then use buffer-string to get the whole buffer content.

;; process string in a temp buffer

(with-temp-buffer
  (insert bigString)

  (goto-char (point-min))

  ;; code to manipulate string. eg delete char, etc

  ;; return whole buffer string
  (buffer-string))

Trim String and Others

These are new string functions. To use them, you need to first (require 'subr-x). New in Emacs 24.4. [see Emacs 24.4 Features (released 2014-10)]

(require 'subr-x)
(string-trim " abc  ")

(info "(elisp) Strings and Characters")

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial

Emacs Tutorial

Emacs Init

Emacs Keys

ELisp

ELisp Examples

ELisp Write Major Mode


ELisp

Basics

Basic Functions

Writing Command

Writing Script

Lisp Data Structure

Lisp Symbol

Elisp Misc