ClojureDocs

Nav

Namespaces

re-matcher

clojure.core

Available since 1.0 (source)
  • (re-matcher re s)
Returns an instance of java.util.regex.Matcher, for use, e.g. in
re-find.
2 Examples
user=> (def *matcher* (re-matcher #"\d+" "abc12345def"))
#'user/*matcher*

user=> (re-find *matcher*)
"12345"
;
; Java supports named capture groups
;
; Define a phone number pattern with some named groups
(let [patt (re-pattern "(?<area>\\d{3})-(?<prefix>\\d{3})-(?<tail>\\d{4})")]
  ; `re-matches` will find the capturing groups and stick them in a vector
  ; after the full match The capture groups are numbered starting with 1.
  ; The full match is like group zero.
  (is= ["619-239-5464" "619" "239" "5464"] (re-matches patt "619-239-5464"))

  ; Construct a java.util.regex.Matcher.  Keep in mind that it is a mutable object!
  (let [matcher (re-matcher patt "619-239-5464")]
    ; Execute the Matcher via `re-find`. It returns all 4 groups and caches them
    (is= ["619-239-5464" "619" "239" "5464"] (re-find matcher))

    ; `re-groups` simply returns the cached result from the Matcher
    (is= ["619-239-5464" "619" "239" "5464"] (re-groups matcher))

    ; We need the instance function Matcher.group( <name> ) to
    ; extract the named group
    (is= "619" (.group matcher "area"))
    (is= "239" (.group matcher "prefix"))
    (is= "5464" (.group matcher "tail"))))
See Also

Returns the next regex match, if any, of string to pattern, using java.util.regex.Matcher.find(). ...

Added by gstamp
2 Notes
    By , created 10.4 years ago

    17:44 < mearnsh> tsdh: re-matcher should be avoided because the Matcher object it returns mutates in a non-thread-safe way

    By , created 9.0 years ago

    It's fine to use from a controlled context. For instance, if you have a let that creates a Matcher, pulls out groups, and returns the data, you're working in a single-threaded context and the mutable object never even escapes.