我想编写一个函数replace-several来接收一个字符串和一组替换并应用所有替换(替换时看到以前替换的结果).
我想到了以下界面:
(replace-several "abc" #"a" "c"
#"b" "l"
#"c" "j"); should return "jlj"
Run Code Online (Sandbox Code Playgroud)
两个问题:
备注:要进行单次替换,可以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)
(str/escape "abc" {\a "c" \b "l" \c "j"})
; => "clj"
Run Code Online (Sandbox Code Playgroud)
文档逃逸
这是另一个镜头,但具有不同的输出结果,这个镜头使用正则表达式引擎功能,因此它可能更快,而且界面也不同,因为它将键映射到替换字符串。我提供这个以防万一它对有类似问题的人有用。
(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"
我参加这个聚会迟到了,但就其价值而言,我认为最惯用的方法是使用线程和多个替换:
(require '[clojure.string :refer [replace])
(-> "abc"
(replace #"a" "c")
(replace #"b" "l")
(replace #"c" "j"))
;=> "jlj"
Run Code Online (Sandbox Code Playgroud)
这句话的意思很清楚,尽管避免多次输入“replace”是很好的。
| 归档时间: |
|
| 查看次数: |
2551 次 |
| 最近记录: |