Emacs Lisp: String Functions

By Xah Lee. Date: . Last updated: .

Here is a complete list of string functions.

Basic String Functions

length
(length SEQUENCE)
Return the length of vector, list or string SEQUENCE.
(length "abc")
;; 3
substring
(substring STRING &optional FROM TO)
return a substring from position FROM to TO. Position start at 0. By default, TO is to end of string, if omitted. FROM is 0. If negative, count from right.
(substring "abc123" 0 3)
;; "abc"
concat
(concat &rest SEQUENCES)
Concatenate all the arguments and make the result a string.
(concat "some" "thing")
split-string
(split-string STRING &optional SEPARATORS OMIT-NULLS TRIM)
Split STRING into substrings bounded by matches for SEPARATORS.
;; split string into parts, returns a list
(split-string "xy_007_cat" "_")

String To/From Number

(string-to-number "3")

(number-to-string 3)

(format "%d" 3)
 ;; same as number-to-string but can also do format

Buffer Text to String

Emacs Lisp: Get Buffer String

String to Buffer

If you got a long string, and need to insert or delete parts often, it's much more efficient to use buffer data type.

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))

Match String by Regex

string-match
(string-match REGEXP STRING &optional START)
Return index of start of first match for REGEXP in STRING, or nil.
(string-match "b+" "abbc")
;; 1

Get Substring by Regex

Use match-string.

(setq myStr "swimming in pool")

(string-match "\\([a-z]+?ing\\) " myStr)

(match-string 1 myStr)
;; "swimming"

Regex Replace in String

replace-regexp-in-string
(replace-regexp-in-string REGEXP REP STRING &optional FIXEDCASE LITERAL SUBEXP START)
Replace string by regex.
(replace-regexp-in-string "</*div>" "<p>" "<div>something</div>")
;; return
;; "<p>something<p>"

See:

Trim String and Others

These are new in Emacs 24.4 (released 2014-10). To use them, you need to first:

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

(info "(elisp) Strings and Characters")

String Functions Reference

Here's a complete list of string functions for reference. If you are a elisp beginner, ignore them.

(info "(elisp) Predicates-for-Strings")

(info "(elisp) Creating-Strings")

(info "(elisp) Modifying-Strings")

(info "(elisp) Text-Comparison")

(info "(elisp) Text-Comparison")

(info "(elisp) Case-Conversion")

(info "(elisp) Case-Tables")

Emacs Lisp String

Lisp Basics

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp