clojure.string/replace-first return nil when not matched

48 views
Skip to first unread message

Takahiro Hozumi

unread,
Mar 10, 2011, 7:39:49 PM3/10/11
to Clojure
Hi,
I have two questions about clojure.string/replace-first.

1.
Is this expected behavior of replace-first?

(require '[clojure.string :as str])
(str/replace-first "abc def" #"ghi" (fn [a] (str a a)))
=> nil

I don't think so, because string / string argument version returns
original string when mismatched.
(str/replace-first "abc def" "ghi" "jkl")
=> "abc def"

2.
Is it difficult that replace-first support argument of string /
function besides regex / function (i.e. without using Pattern/quote)?

(str/replace-first "abc def" "def" (fn [a] (str a a)))
=> "abc defdef"

The reason why I'd like to avoid using Pattern/quote is that ,I think,
to replace string with string should be more lightweight than with
regex.

Thanks.

Armando Blancas

unread,
Mar 10, 2011, 11:30:45 PM3/10/11
to Clojure
1. The Clojure wrapper put the last two calls inside the if, unlike
Matcher#replaceFirst(), thus the nil.

public String replaceFirst(String replacement) {
if (replacement == null)
throw new NullPointerException("replacement");
StringBuffer sb = new StringBuffer();
reset();
if (find())
appendReplacement(sb, replacement);
appendTail(sb);
return sb.toString();
}

(defn- replace-first-by
[^CharSequence s ^Pattern re f]
(let [m (re-matcher re s)]
(let [buffer (StringBuffer. (.length s))]
(if (.find m)
(let [rep (f (re-groups m))]
(.appendReplacement m buffer rep)
(.appendTail m buffer)
(str buffer))))))

Stuart Sierra

unread,
Mar 11, 2011, 8:55:12 AM3/11/11
to clo...@googlegroups.com
(require '[clojure.string :as str])
(str/replace-first "abc def" #"ghi" (fn [a] (str a a)))
=> nil


Thanks for the report.

-Stuart Sierra

Takahiro Hozumi

unread,
Mar 20, 2011, 12:06:59 PM3/20/11
to Clojure
Hi,
Please bump up my JIRA membership level to make edits and I will fix
this bug.
I have an account named Takahiro Hozumi on dev.clojure.org already.
CA is also already sent.
Thanks.
Reply all
Reply to author
Forward
0 new messages