You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:57:05