如果 Clojure 中存在,则替换字符串中的某些内容

hin*_*awa 0 string clojure

我已经搜索了该网站,但没有找到我关于子字符串替换的特定问题的合适答案。我知道如何通过替换子字符串/正则表达式clojure.string/replace但不确定在这种情况下使用它。

让我们说。我首先有一些字符串:

(def test-str "I am a test string. :name to replace, :age to replace. And there are strange symbols in this string. And here are the keyword shall not modify, such as :not-interested.")
(def another-test-str ":nothing :to :replace")
Run Code Online (Sandbox Code Playgroud)

我有一个翻译表:

(def translation-table {:name "Alice"
                :age  19})
Run Code Online (Sandbox Code Playgroud)

我想,以取代:nametest-str与“爱丽丝”,:age与19,但不希望更换:not-interested。表很长,不同的字符串(要替换)包含不同的关键字。

鉴于翻译表,那么进行子串替换的可能系统方法是什么?即,我想要一个函数replace-with-translation

(replace-with-translation test-str translation-table)
=> "I am a test string. Alice to replace, 19 to replace. And there are strange symbols in this string. And here are the keyword shall not modify, such as :not-interested."

(replace-with-translation another-test-str translation-table)
=> ":nothing :to :replace"

(replace-with-translation test-str {})
=> "I am a test string. :name to replace, :age to replace. And there are strange symbols in this string. And here are the keyword shall not modify, such as :not-interested."
Run Code Online (Sandbox Code Playgroud)

Bip*_*ill 6

string/replace可以使用函数作为替换,并且get(从地图中检索)采用可选参数以在条目丢失的情况下使用。这些功能共同构成了一个简洁的解决方案:

(require '[clojure.string :as string])

(defn replace-with-translation [s m]
  (string/replace s #":([-_a-zA-Z0-9]+)" 
    (fn [[r k]]
      (str (get m (keyword k) r)))))
Run Code Online (Sandbox Code Playgroud)

PS 该正则表达式并不能完全说明所有可能的关键字,但如果它满足您的要求,那么它的优势很可能也适用于 ClojureScript。