re-pattern

Returns an instance of java.util.regex.Pattern, for use, e.g. in re-matcher. Clojure also provides a handy literal syntax for regular expressions: #"regex here".

(re-pattern "\\d+")
;=> #"\d+"

(type #"\d+")
;=> java.util.regex.Pattern

re-matcher

Returns an instance of java.util.regex.Matcher, for use, e.g. in re-find.

From javadoc: Once created, a matcher can be used to perform three different kinds of match operations:

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

re-matches

using java.util.regex.Matcher.matches(), attempts to match the entire string against the pattern.

(re-matches #"hello" "hello, world")
;=> nil

(re-matches #"hello.*" "hello, world")
;=> "hello, world"

(re-matches #"hello, (.*)" "hello, world")
;=> ["hello, world" "world"]

re-find

using java.util.regex.Matcher.find(), attempts to find the next subsequence of the input sequence that matches the pattern.

  • (re-find re s): returns the first match
(re-find #"\d+" "abc12345def")
;=> "12345"

; if there are groups in the pattern, re-find returns a vector:
; the first item is the part of the string that matches the entire pattern,
; and each successive item are the parts of the string that matched the 1st, 2nd, etc. groups.
(def line " RX packets:1871074138 errors:5 dropped:48 overruns:9")
(re-find #"(\S+):(\d+)" line)
;=> ["packets:1871074138" "packets" "1871074138"]
  • (re-find matcher): returns the next regex match
(def phone-number "672-345-456-3212")

(def matcher (re-matcher #"\d+" phone-number)) ; an instance of java.util.regex.Matcher

; iterate through all matches
(while (re-find matcher)        ; when there's no more valid matches, nil is returned
  (println (re-groups matcher)) ; use re-groups to get the most recent match/find
  )
; 672
; 345
; 456
; 3212

re-seq

return all matches as a sequence

(re-seq #"\d" "clojure 1.1.0")
;=> ("1" "1" "0")