Skip to content

Instantly share code, notes, and snippets.

@cgrand
Created April 12, 2010 10:34
Show Gist options
  • Save cgrand/363438 to your computer and use it in GitHub Desktop.
Save cgrand/363438 to your computer and use it in GitHub Desktop.
;; Growing a little DSL for regexes
;; prompted by http://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings
(defmulti pattern type)
(defn regex [spec]
(-> spec pattern java.util.regex.Pattern/compile))
(defmethod pattern String [s]
(java.util.regex.Pattern/quote s))
(defmethod pattern clojure.lang.IPersistentSet [alts]
(str "(?:" (->> alts (map regex) (interpose \|) (apply str)) ")"))
(defmethod pattern clojure.lang.IPersistentVector [alts]
(str "(?:" (->> alts (map regex) (apply str)) ")"))
(comment
user=> (def forbidden-words [":)" "the" "." ","])
user=> (def strings ["the movie list" "this.is.a.string" "haha :)"])
user=> (map #(.replaceAll % (-> forbidden-words set pattern) "") strings)
(" movie list" "thisisastring" "haha ")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment