Created
April 12, 2010 10:34
-
-
Save cgrand/363438 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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