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
python
transformed = re.sub(r'\{(\w+)\}',
lambda match: match.group(1)[::-1],
'The {Quick} Brown {Fox}')
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))))
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
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));

Submit a new solution for python, clojure, fsharp, or cpp
There are 9 other solutions in additional languages (erlang, fantom, groovy, java ...)