Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

file 41 lines (32 sloc) 1.163 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
(ns clojure.core.match.regex
  (:use [clojure.core.match
         :only [emit-pattern to-source pattern-equals
                pattern-compare comparable?]])
  (:import java.util.regex.Pattern))

;; # Regular Expression Extension
;;
;; This extension adds support for Clojure's regular expression syntax.

(defrecord RegexPattern [regex])

(defmethod emit-pattern java.util.regex.Pattern
  [pat]
  (RegexPattern. pat))

;; Regular expressions are matched with `re-matches`.
;;
;; For example, given a pattern `#"olive"` and occurance `q`, a match occurs
;; when this expression is true:
;;
;; `(re-matches #"olive" q)`

(defmethod to-source RegexPattern
  [pat ocr]
  `(re-matches ~(:regex pat) ~ocr))


;; `java.util.regex.Pattern` doesn't override `equals`, so we reinvent it here.
;;
;; Two `Pattern`s are equal if they have the same pattern and the same flags.

(defmethod pattern-compare [RegexPattern RegexPattern]
  [a b] (if (and (= (.pattern ^Pattern (:regex a)) (.pattern ^Pattern (:regex b)))
                 (= (.flags ^Pattern (:regex a)) (.flags ^Pattern (:regex b))))
          0
          -1))

(defmethod comparable? RegexPattern
  [x]
  false)
Something went wrong with that request. Please try again.