如何在Clojure中实现用于替换第二个匹配项的replace-second函数?
Clojure替换字符串第二个匹配项实现
现有替换第一个匹配项的原生用法如下:
(clojure.string/replace-first "a x x c d" #"x" "b") ; 替换第一个匹配的x
方案1:独立实现replace-second函数
直接针对替换第二个匹配的场景编写函数,匹配项不足2个时会直接返回原字符串:
(defn replace-second [s pattern replacement] (let [matcher (re-matcher pattern s)] (if (.find matcher) (if (.find matcher) (str (subs s 0 (.start matcher)) replacement (subs s (.end matcher))) s) s)))
测试调用示例:(replace-second "a x x c d" #"x" "b")
返回结果:"a x b c d"
方案2:通用替换第N个匹配项函数
如果后续有替换第3、第N个匹配的需求,可以先封装通用的replace-nth函数,再基于它实现replace-second,入参规则和原生replace-first保持一致:
;; 通用替换第n个匹配项,n从1开始计数 (defn replace-nth [s pattern replacement n] {:pre [(pos? n)]} (let [matcher (re-matcher pattern s)] (loop [current 1] (if (.find matcher) (if (= current n) (str (subs s 0 (.start matcher)) replacement (subs s (.end matcher))) (recur (inc current))) s)))) ;; 基于通用函数实现replace-second (defn replace-second [s pattern replacement] (replace-nth s pattern replacement 2))
内容的提问来源于stack exchange,提问作者Shamir George
相关产品推荐
相关产品推荐

