【问题标题】:How to replace substrings?如何替换子字符串?
【发布时间】:2016-09-29 00:53:16
【问题描述】:

我有这个:

(defn page1 []
  (layout/render
   "index.html" 
   ({:articles (db/get-articles)})))

功能

db/get-articles

返回具有键体的对象列表。我需要解析文章的正文,如果存在的话,用"bbb13bbb" 替换子字符串"aaa12aaa",用"bbb23bbb" 替换"aaa22aaa" 等等。我该怎么做才能不消耗大量内存?使用正则表达式有效吗?

更新:

我需要替换的模式是:“[something="X" something else/]”。其中 X 是一个数字,它是未知的。我需要改变 X。 可以有许多这样的模式可以替换,也可以没有。

【问题讨论】:

    标签: clojure compojure luminus


    【解决方案1】:

    我只会使用 Java 的 String.replace 或 String.replaceAll 或 clojure.string 函数:replace/replace-first。

    我不会浪费时间进行过早的优化,并首先衡量简单的解决方案是否有效。我不确定文章内容有多大,但我想这应该不是问题。

    如果事实证明您确实需要优化,那么也许您应该切换到从数据存储中流式传输您的文章内容,并手动实现替换或使用 streamflyer 之类的库在发送之前即时执行修改文章内容到 HTTP 响应流。

    【讨论】:

      【解决方案2】:

      这样的事情应该很快:

      (mapv
        (fn [{:keys [body] :as m}]
          (assoc m :body
                   (reduce-kv
                     (fn [body re repl]
                       (string/replace body re repl))
                     body
                     {"aaa12aaa" "bbb13bbb",
                      "aaa22aaa" "bbb23bbb"})))
        [{:body "xy aaa12aaa fo aaa22aaa"}])
      

      如果你能保证字符串只出现一次你可以用replace-first替换replace。

      【讨论】:

        【解决方案3】:

        正则表达式在 clojure 中效果很好:

        (ns clj.core
          (:use tupelo.core)
          (:require
            [clojure.string :as str]
            )
        
        (spyx (str/replace "xyz-aaa12aaa-def" #"aaa12aaa" "bbb13bbb"))
        
        ;=>  (str/replace "xyz-aaa12aaa-def" #"aaa12aaa" "bbb13bbb") => "xyz-bbb13bbb-def"
        

        【讨论】:

        • 另请注意,您可以使用它进行“计算”(inc 12):(clojure.string/replace "xyz-aaa12aaa-def" #"(aaa)(\d\d)(aaa)" (fn [[_ _ n _]] (str "bbb" (inc (Integer/parseInt n)) "bbb")))
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        • 2014-05-18
        • 2011-09-01
        • 2013-05-18
        • 2015-11-13
        • 2020-04-05
        • 2019-04-15
        相关资源
        最近更新 更多