Clojure: regex

By Xah Lee. Date: . Last updated: .

This page is WORK IN PROGRESS.

Create Regex Pattern Object

#"…" create a regex pattern object. This is same as (re-pattern )

(re-pattern regex_string)
Return a regex pattern object. clojure.core/re-pattern

Note: Clojure regex is basically a wrapper on Java's regex. re-pattern returns a instance of Java's java.util.regex.Pattern

;; creates a regex object

;; this is equivalent to

(re-pattern "abc")
(re-matches re s)
Return the match, if any, of string to pattern, using java.util.regex.Matcher.matches(). Uses re-groups to return the groups. clojure.core/re-matches
;; “re-matches” check if entire string matches a regex
;; if so, returns the matched string, else nil
;; note: must match the whole string

(re-matches #"a" "abc") ; ⇒ nil

(re-matches #"a.+" "abc") ; ⇒ "abc"
(re-matcher re s)
Return an instance of java.util.regex.Matcher, for use, e.g. in re-find. clojure.core/re-matcher
(re-matcher re s)
Return a match object. (it is a instance of java.util.regex.Matcher). The matcher object contains all the regex match info. You can use other functions to query it, such as re-find.

re-find. clojure.core/re-matcher

(re-seq #"[0-9]+" "abs123def345ghi567")

;; ("123" "345" "567")

(re-find #"([-+]?[0-9]+)/([0-9]+)" "22/7")
;; ["22/7" "22" "7"]

(let [[a b c] (re-matches #"([-+]?[0-9]+)/([0-9]+)" "22/7")]
         [a b c])
;; ["22/7" "22" "7"]

(re-seq #"(?i)[fq].." "foo bar BAZ QUX quux")
;; ("foo" "QUX" "quu")
(re-groups m)
Return the groups from the most recent match/find. If there are no nested groups, returns a string of the entire match. If there are nested groups, returns a vector of the groups, the first element being the entire match. clojure.core/re-groups
(re-seq re s)
Return a lazy sequence of successive matches of pattern in string, using java.util.regex.Matcher.find(), each such match processed with re-groups. clojure.core/re-seq

(re-find m)

(re-find re s)
Return the next regex match, if any, of string to pattern, using java.util.regex.Matcher.find(). Uses re-groups to return the groups. clojure.core/re-find

Clojure Regex Patterns

Clojure uses the regex engine of the hosted platform. So, normally, its regex is Java's regex.

Java regex syntax is largely the same as perl, python, for the basic features that are used 99% of the time.