Wolfram: String Replace

By Xah Lee. Date: . Last updated: .

Replace by Index Range

StringReplacePart[ str, newStr, {m,n}]

replace string by position range.

if m or n are negative, count from right.

StringReplacePart[ "123456", "xx", {1,1}]
(* xx23456 *)

StringReplacePart[ "123456", "xx", {1,4}]
(* xx56 *)
StringReplacePart[ "123456", "x", {-2,-1}]
(* 1234x *)
StringReplacePart[ str, newStr, list_of_range]

replace multiple ranges.

StringReplacePart[ "123456", "xx", {{1,1}, {3,3}}]
(* xx2xx456 *)
StringReplacePart[ str, list_of_newstr, list_of_range]

replace by multiple strings into corresponding index ranges.

StringReplacePart[ "123456",
{"a", "b", "c"},
{{1,1}, {3,3}, {5,6}}
]
(* a2b4c *)

Replace by Pattern

StringReplace[ str , findStr -> replaceStr]

replace string.

the findStr can be a pattern, represented by Regular Expression or String Expression

StringReplace[ "some dogs" , "dog" -> "cat"]
(* "some cats" *)
(* replace letter prefixed digits by x prefix *)

StringReplace[ "good g935 m66 z024 m12 g904 q08",
 RegularExpression["[a-z](\\d+)"] -> "x$1"
]
(* good x935 x66 x024 x12 x904 x08 *)
StringReplace[ str , rulesList]

Replace multiple pairs of strings. Replacement does not depend on previous replacement.

(* replace multiple pairs of strings. replacement does not depend on previous replacement. *)

StringReplace["abc", {"a"->"x", "b"->"y", "x"->"H"}]
(* xyc *)

Wolfram. String