Browse files

collapse the replace-first-* fns, align arg order with clojure conven…


Signed-off-by: Stuart Halloway <>
  • Loading branch information...
David Liebke and Stuart Halloway authored and stuarthalloway committed May 28, 2010
1 parent 8efeb01 commit f4427c70bd7c711b3a9c49f0a2e5f6781be707e1
Showing with 18 additions and 14 deletions.
  1. +15 −12 src/clj/clojure/string.clj
  2. +3 −2 test/clojure/test_clojure/string.clj
@@ -45,20 +45,10 @@
(replace-by s match replacement))
:default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
-(defn replace-first-str
- "Replace first occurance of substring a with b in s."
- [^String a ^String b ^String s]
- (.replaceFirst (re-matcher (Pattern/quote a) s) b))
-(defn replace-first-re
- "Replace first match of re in s."
- [^Pattern re ^String replacement ^String s]
- (.replaceFirst (re-matcher re s) replacement))
-(defn replace-first-by
+(defn- replace-first-by
"Replace first match of re in s with the result of
(f (re-groups the-match))."
- [^Pattern re f ^String s]
+ [^String s ^Pattern re f]
(let [m (re-matcher re s)]
(let [buffer (StringBuffer.)]
(if (.find m)
@@ -67,6 +57,19 @@
(.appendTail m buffer)
(str buffer))))))
+(defn replace-first
+ ""
+ [^String s match replacement]
+ (cond
+ (instance? String match)
+ (.replaceFirst s (Pattern/quote ^String match) ^String replacement)
+ (instance? Pattern match)
+ (if (string? replacement)
+ (.replaceFirst (re-matcher ^Pattern match s) ^String replacement)
+ (replace-first-by s match replacement))
+ :default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
(defn ^String join
"Returns a string of all elements in coll, separated by
separator. Like Perl's join."
@@ -11,8 +11,9 @@
(is (= "FOObarFOO" (s/replace "foobarfoo" #"foo" s/upper-case))))
(deftest t-replace-first
- (is (= "barbarfoo" (s/replace-first-re #"foo" "bar" "foobarfoo")))
- (is (= "FOObarfoo" (s/replace-first-by #"foo" s/upper-case "foobarfoo"))))
+ (is (= "barbarfoo" (s/replace-first "foobarfoo" "foo" "bar")))
+ (is (= "barbarfoo" (s/replace-first "foobarfoo" #"foo" "bar")))
+ (is (= "FOObarfoo" (s/replace-first "foobarfoo" #"foo" s/upper-case))))
(deftest t-join
(are [x coll] (= x (s/join coll))

0 comments on commit f4427c7

Please sign in to comment.