View Subcategory

Replace the first regex match in a string with a static string

Transform "Red Green Blue" into "R*d Green Blue" by replacing /e/ with "*"
clojure
(.replaceFirst (re-matcher #"e" "Red Green Blue") "*")
cpp
String^ Replaced = (gcnew Regex("e"))->Replace("Red Green Blue", "*", 1);

Replace all regex matches in a string with a static string

Transform "She sells sea shells" into "She X X shells" by replacing /se\w+/ with "X"
csharp
using System.Text.RegularExpressions;

class SolutionXX
{
static void Main()
{
string text = "She sells sea shells";
string result = Regex.Replace(text, @"se\w+", "X");
}
}
clojure
(.replaceAll (re-matcher #"se\w+" "She sells sea shells") "X")
cpp
String^ Replaced = (gcnew Regex("se\\w+"))->Replace("She sells sea shells", "X");
String^ Replaced = Regex::Replace("She sells sea shells", "se\\w+", "X");

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+)\}/.
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))))))
(clojure.string/replace "The {Quick} Brown {Fox}"
#"\{(\w+)\}"
(fn [[_ word]] (apply str (reverse word))))
cpp
String^ Replaced = (gcnew Regex("{(\\w+)}"))->Replace("The {Quick} Brown {Fox}", gcnew MatchEvaluator(&RegRep::RepGroup));
String^ Replaced = Regex::Replace("The {Quick} Brown {Fox}", "{(\\w+)}", gcnew MatchEvaluator(&RegRep::RepGroup));