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) → returns 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. Pattern (Java Platform SE 8 )

;; creates a regex object

;; this is equivalent to

(re-pattern "abc")

(re-matches re s) → Returns 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

Matcher (Java Platform SE 8 )#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) → Returns an instance of java.util.regex.Matcher, for use, e.g. in re-find. clojure.core/re-matcher

(re-matcher re s) → Returns 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

Matcher (Java Platform SE 8 )

(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) → Returns 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) → Returns 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) → Returns 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.

Pattern (Java Platform SE 8 )