Browse files

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

…tion

Signed-off-by: Stuart Halloway <stu@thinkrelevance.com>
  • Loading branch information...
1 parent 8c0022f commit 8efeb01d4c617283a8710481f4ac41af8b64408e David Liebke and Stuart Halloway committed with stuarthalloway May 28, 2010
Showing with 22 additions and 22 deletions.
  1. +19 −19 src/clj/clojure/string.clj
  2. +3 −3 test/clojure/test_clojure/string.clj
View
38 src/clj/clojure/string.clj
@@ -17,25 +17,8 @@
[^String s]
(.toString (.reverse (StringBuilder. s))))
-(defn replace-str
- "Replaces all instances of substring a with b in s."
- [^String a ^String b ^String s]
- (.replace s a b))
-
-(defn replace-char
- "Replaces all instances of character a with character b in s."
- [^Character a ^Character b ^String s]
- (.replace s a b))
-
-(defn replace-re
- "Replaces all matches of re with replacement in s."
- [re replacement ^String s]
- (.replaceAll (re-matcher re s) replacement))
-
-(defn replace-by
- "Replaces all matches of re in s with the result of
- (f (re-groups the-match))."
- [re f ^String s]
+(defn- replace-by
+ [^String s re f]
(let [m (re-matcher re s)]
(let [buffer (StringBuffer. (.length s))]
(loop []
@@ -45,6 +28,23 @@
(do (.appendTail m buffer)
(.toString buffer)))))))
+(defn replace
+ "Replaces all instance of match with replacement in s.
+
+ match/replacement can be:
+
+ string / string
+ char / char
+ pattern / (string or function of match)"
+ [^String s match replacement]
+ (cond
+ (instance? Character match) (.replace s ^Character match ^Character replacement)
+ (instance? String match) (.replace s ^String match ^String replacement)
+ (instance? Pattern match) (if (string? replacement)
+ (.replaceAll (re-matcher ^Pattern match s) ^String replacement)
+ (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]
View
6 test/clojure/test_clojure/string.clj
@@ -6,9 +6,9 @@
(is (= "tab" (s/reverse "bat"))))
(deftest t-replace
- (is (= "faabar" (s/replace-char \o \a "foobar")))
- (is (= "barbarbar" (s/replace-str "foo" "bar" "foobarfoo")))
- (is (= "FOObarFOO" (s/replace-by #"foo" s/upper-case "foobarfoo"))))
+ (is (= "faabar" (s/replace "foobar" \o \a)))
+ (is (= "barbarbar" (s/replace "foobarfoo" "foo" "bar")))
+ (is (= "FOObarFOO" (s/replace "foobarfoo" #"foo" s/upper-case))))
(deftest t-replace-first
(is (= "barbarfoo" (s/replace-first-re #"foo" "bar" "foobarfoo")))

0 comments on commit 8efeb01

Please sign in to comment.