在clojure中,如何编写一个应用多个字符串替换的函数?

vie*_*bel 8 clojure

我想编写一个函数replace-several来接收一个字符串和一组替换并应用所有替换(替换时看到以前替换的结果).

我想到了以下界面:

(replace-several "abc" #"a" "c" 
                       #"b" "l"
                       #"c" "j"); should return "jlj" 
Run Code Online (Sandbox Code Playgroud)

两个问题:

  1. 它是clojure中最惯用的界面吗?
  2. 如何实现这个功能?

备注:要进行单次替换,可以replace使用clojure.string.

vie*_*bel 13

使用和实施@ kotarak的建议replace,reduce并且partition:

(defn replace-several [content & replacements]
      (let [replacement-list (partition 2 replacements)]
        (reduce #(apply string/replace %1 %2) content replacement-list)))
; => (replace-several "abc" #"a" "c" #"b" "l" #"c" "j")
  "jlj"
Run Code Online (Sandbox Code Playgroud)


kot*_*rak 9

所以你有replace,reducepartition.从这些构建块中,您可以构建您的replace-several.


mag*_*pie 6

(str/escape "abc" {\a "c" \b "l" \c "j"})

; => "clj"
Run Code Online (Sandbox Code Playgroud)

文档逃逸

  • 谢谢你的这块金子。我完全错过了“逃脱”。很不错。将其添加到箭袋中。 (3认同)

bmi*_*are 5

这是另一个镜头,但具有不同的输出结果,这个镜头使用正则表达式引擎功能,因此它可能更快,而且界面也不同,因为它将键映射到替换字符串。我提供这个以防万一它对有类似问题的人有用。

(defn replace-map
  "given an input string and a hash-map, returns a new string with all
  keys in map found in input replaced with the value of the key"
  [s m]
  (clojure.string/replace s
              (re-pattern (apply str (interpose "|" (map #(java.util.regex.Pattern/quote %) (keys m)))))
          m))
Run Code Online (Sandbox Code Playgroud)

所以用法是这样的:

 (replace-map "abc" {"a" "c" "b" "l" "c" "j"})
Run Code Online (Sandbox Code Playgroud)

=> "clj"


dan*_*cox 5

我参加这个聚会迟到了,但就其价值而言,我认为惯用的方法是使用线程和多个替换:

(require '[clojure.string :refer [replace])

(-> "abc"
    (replace #"a" "c")
    (replace #"b" "l")
    (replace #"c" "j"))

;=> "jlj"
Run Code Online (Sandbox Code Playgroud)

这句话的意思很清楚,尽管避免多次输入“replace”是很好的。