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
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
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),
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
DiskEdit
fsharp
open System
open System.Text.RegularExpressions
let reverseMatch (m:Match) =
String(m.Groups.[1].Value.ToCharArray() |> Array.rev)
let output = Regex.Replace("The {Quick} Brown {Fox}", @"\{(\w+)\}", reverseMatch)
ExpandDiskEdit
groovy
replaced = "The {Quick} Brown {Fox}".replaceAll(/\{(\w+)\}/, { full, word -> word.reverse() } )
ExpandDiskEdit
java 1.4 or later
Matcher m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}");
StringBuffer sb = new StringBuffer(32), rsb = new StringBuffer(8);

while (m.find())
{
rsb.replace(0, rsb.length(), m.group(1)); rsb.reverse(); m.appendReplacement(sb, rsb.toString());
}
m.appendTail(sb);
ExpandDiskEdit
ocaml
let s = "The {Quick} Brown {Fox}" in
let r = Str.regexp "{\\([^ \\t\\n]*\\)}" in
Str.global_substitute r (fun m -> string_rev (Str.matched_group 1 m)) s
DiskEdit
perl
$text = "The {Quick} Brown {Fox}";
$text =~ s/\{(\w+)\}/reverse($1)/ge;
ExpandDiskEdit
php
// We have to use the e-modifier
preg_replace("/\{(\w+)\}/e", "''.strrev('\\1').''", "The {Quick} Brown {Fox}");
DiskEdit
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
DiskEdit
ruby
"The {Quick} Brown {Fox}".gsub(/\{(\w+)\}/) {|s| s[1..-2].reverse }
ExpandDiskEdit
scala
val m = Pattern.compile("\\{(\\w+)\\}").matcher("The {Quick} Brown {Fox}")
val sb = new StringBuffer(32) ; val rsb = new StringBuffer(8)

while (m.find) { rsb.replace(0, rsb.length, m.group(1)) ; m.appendReplacement(sb, rsb.reverse.toString) }
m.appendTail(sb)

Submit a new solution for clojure, cpp, erlang, fantom ...