Emacs Lisp: Regex Functions

By Xah Lee. Date: . Last updated: .

The most frequently used regex function are:

(re-search-forward REGEXP &optional BOUND NOERROR COUNT)
search a regex pattern starting from cursor position, towards right. If found, move cursor at the end of matched text. If not found, don't move cursor.
  • BOUND → is a position. Means don't search beyond it.
  • NOERROR → is boolean. True means don't error if none found.
  • COUNT → default to 1. Else, search that many times. If negative, search backward.
(aliased to search-forward-regexp.)
(let ((case-fold-search nil))
  (re-search-forward "[0-9]+"))
;; 100 cats
(re-search-backward args)
same as re-search-forward but search backward, however, searching backward may stop at a position that's not maximally matched by pattern.
(aliased to search-backward-regexp)
(skip-chars-forward STRING &optional LIM)
Move point forward, stopping before a char not in STRING, or at pos LIM. STRING is like the inside of a [chars] in a Regular Expression Syntax except that ] is never special and \ quotes ^ , - or \
(skip-chars-backward STRING &optional LIM)
same as skip-chars-forward but backward.
(string-match REGEXP STRING &optional START)
match a string with regexp. Result is true when matched, else nil

Get Captured Group

(match-string n)
get the nth captured string. 0 means the whole matched pattern.
(match-string-no-properties n)
same as match-string but no Text Properties
(let ((case-fold-search nil))
  (re-search-forward "\\([0-9]+\\)")
  ;; lots text 123 abc
  (match-string-no-properties 1)
)
; "123"
(match-beginning n)
get the beginning position of the nth captured string in buffer.
(let ((case-fold-search nil) p1 p2)
  (re-search-forward "\\([0-9]+\\)")
  (setq p1 (match-beginning 1))
  (setq p2 (match-end 1))
  (buffer-substring-no-properties p1 p2))
;; lots sample text 123 abc
;; "123"
(match-end n)
get the end position of the nth captured string in buffer.

Replace Match

(replace-match NEWTEXT &optional FIXEDCASE LITERAL STRING SUBEXP)
Replace the matched pattern of previous regex function call.
(let ((case-fold-search nil))
  (re-search-forward "[0-9]+")
  (replace-match "gazillion"))
;; 100 cats

Emacs Regular Expression

Regex in Emacs Lisp

ErgoEmacs mascot-s276x226
Buy Xah Emacs Tutorial

Lisp Basics

Basics

Lisp Data Structure

Function

Lisp Symbol

Lisp Misc

Working with Elisp