我有一個函式,它接受一個字串s和一個字符映射charmap。如果字串中的任何字符在s內charmap,則將該字符替換為映射的值。
注意,映射中的鍵必須是字串,而不是字符。
例如:
(replace-characters "Hi!" {"!" "Exclamation Mark"}) ;; => "HiExclamation Mark"
這是我目前使用的代碼:
(defn- replace-characters
"Replaces any characters in a string that are mapped in the given charmap"
[s charmap]
(let [character-set (set s)
characters (filter #(contains? charmap (str %)) character-set)]
(string/replace s (re-pattern (string/join "|" characters)) charmap)))
但是,我得到了一個NullPointerException,我對為什么感到非常困惑。
java.lang.NullPointerException: Cannot invoke "String.indexOf(int)" because "s" is null
我想最好在純 Clojure 中解決這個問題,而不是 Java 等。
更新:所以上面的代碼在 repl 中作業。這很好。但由于某種原因,以下是導致錯誤的原因:
(-> s
(string/replace #"[:/?#\[\]@!$&'()* ,;=]" "")
(replace-characters charmap)) ;; Where charmap is a large map of key value characters.
uj5u.com熱心網友回復:
這是導致錯誤的運算式:
(str/replace "Hi" #"" {"!" "Exclamation Mark"})
("!"被正則運算式替換為"",character-set具有值#{\H \i}和charactersis (),所以用re-patternis創建的模式#""。)
空正則運算式匹配字母之間的每個空格:
(str/replace "Hi" #"" " ")
=> " H i "
因此,replace正在尋找替換 hash-map {"!" "Exclamation Mark"},但沒有找到任何東西 - 沒有 key "":
(str/replace "Hi" #"" {"!" "Exclamation Mark"})
=> error
(str/replace "Hi" #"" {"" " "})
=> " H i "
一種可能的解決方案是簡化定義replace-characters(此解決方案僅適用于非空charmap):
(defn replace-characters [s charmap]
(str/replace s (re-pattern (str/join "|" (keys charmap)))
charmap))
測驗:
(replace-characters "Hi!" {"!" "Exclamation Mark"})
=> "HiExclamation Mark"
(-> "Hi!"
(str/replace #"[:/?#\[\]@!$&'()* ,;=]" "")
(replace-characters {"!" "Exclamation Mark"}))
=> "Hi"
uj5u.com熱心網友回復:
我會選擇這樣簡單的東西:
(apply str (replace {"!" "[exclamation mark]"
"?" "[question mark]"}
(map str "is it possible? sure!")))
;;=> "is it possible[question mark] sure[exclamation mark]"
或這種方式與換能器:
(apply str (eduction (map str) (replace {"!" "[exclamation mark]"
"?" "[question mark]"})
"is it possible? sure!"))
或者可能是這樣的:
(defn replace-characters [s rep]
(apply str (map #(rep (str %) %) s)))
user> (replace-characters "is it possible? sure!" {"!" "[exclamation mark]"
"?" "[question mark]"})
;;=> "is it possible[question mark] sure[exclamation mark]"
uj5u.com熱心網友回復:
string/escape完全符合您的要求:
(string/escape "Hi!" {\! "Exclamation Mark"})
;; => "HiExclamation Mark"
該函式使用從字符到替換的映射替換字符。
如果要替換正則運算式或字串,可以reduce-kv結合使用string/replace:
(def replacements
(array-map
"!" "Exclamation Mark"
#"[:/?#\[\]@!$&'()* ,;=]" ""
#_more_replacements))
(defn replace [s replacements]
(reduce-kv string/replace s replacements))
因此,您在替換的鍵和值上回圈(按順序,何時replacements是)并使用它們將它們應用于字串。array-mapsstring/replace
(replace "Hi!" replacements)
;; => "HiExclamation Mark"
如果 中的元素順序array-map顛倒了 ! with ""(since ! is in the regex) 會成功:
(replace "Hi!" (into (array-map) (reverse replacements)))
;; => "Hi"
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/476254.html
下一篇:如何在R中構造復雜的字串
