View Problem

Replace all regex matches in a string with a dynamic string

Transform "The {Quick} Brown {Fox}" into "The kciuQ Brown xoF" by reversing words in braces using the regex /\{(\w+)\}/.
DiskEdit
ruby
"The {Quick} Brown {Fox}".gsub(/\{(\w+)\}/) {|s| s[1..-2].reverse }
DiskEdit
clojure
(def *string* "The {Quick} Brown {Fox}")
(def *regex* (re-pattern #"\{(\w+)\}"))

(println
(loop [result ""
src *string*
replace-strs (re-seq *regex* *string*)]
(if (empty? src)
result
(let [[match replacement] (first replace-strs)]
(if (= (first src) (first match))
; At the beginning of a sequence that should be replaced.
; Do replacement of a single match
(recur (str result (apply str (reverse replacement)))
(drop (count match) src)
(rest replace-strs))
; else, just copy one char from the source to the result
(recur (str result (first src))
(rest src)
replace-strs))))))
DiskEdit
clojure
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ Replaced = (gcnew Regex("{(\\w+)}"))->Replace("The {Quick} Brown {Fox}", gcnew MatchEvaluator(&RegRep::RepGroup));
ExpandDiskEdit
cpp C++/CLI .NET 2.0
String^ Replaced = Regex::Replace("The {Quick} Brown {Fox}", "{(\\w+)}", gcnew MatchEvaluator(&RegRep::RepGroup));
ExpandDiskEdit
fantom
s := "The {Quick} Brown {Fox}"
m := Regex<|\{(\w+)\}|>.matcher(s)
buf := StrBuf(s.size)
last := 0
while (m.find)
{
buf.add(s[last..m.start-1]).add(m.group(1).reverse)
last = m.end
}
buf.add(s[last..-1])
replaced := buf.toStr
ExpandDiskEdit
erlang
% Erlang regular expressions lack both group capture and backreferences, thus this problem is not directly
% solvable. Presented solution is close, but not on-spec

String = "The {Quick} Brown {Fox}",
{match, FieldList} = regexp:matches(String, "\{([A-Za-z0-9_]+)\}"),

NewString = lists:foldl(fun ({Start, Length}, S) -> replstr(S, lists:reverse(string:substr(S, Start, Length)), Start) end, String, FieldList),

Submit a new solution for ruby, csharp, clojure, cpp ...
There are 8 other solutions in additional languages (fsharp, groovy, java, ocaml ...)