How to remove list of words from strings

两盒软妹~` 提交于 2019-12-12 10:40:02

问题


What I would like to do (in Clojure):

For example, I have a vector of words that need to be removed:

(def forbidden-words [":)" "the" "." "," " " ...many more...])

... and a vector of strings:

(def strings ["the movie list" "this.is.a.string" "haha :)" ...many more...])

So, each forbidden word should be removed from each string, and the result, in this case, would be: ["movie list" "thisisastring" "haha"].

How to do this ?


回答1:


(def forbidden-words [":)" "the" "." ","])
(def strings ["the movie list" "this.is.a.string" "haha :)"])
(let [pattern (->> forbidden-words (map #(java.util.regex.Pattern/quote %)) 
                (interpose \|)  (apply str))]
  (map #(.replaceAll % pattern "") strings))



回答2:


(use 'clojure.contrib.str-utils)
(import 'java.util.regex.Pattern)
(def forbidden-words [":)" "the" "." "," " "])
(def strings ["the movie list" "this.is.a.string" "haha :)"])
(def regexes (map #(Pattern/compile % Pattern/LITERAL) forbidden-words))
(for [s strings] (reduce #(re-gsub %2 "" %1) s regexes))



回答3:


Using function composition and the -> macro this can be nice and simple:

(for [s strings] 
  (-> s ((apply comp 
           (for [s forbidden-words] #(.replace %1 s ""))))))

If you want to be more 'idiomatic', you can use replace-str from clojure.contrib.string, instead of #(.replace %1 s "").

No need to use regexs here.



来源:https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!