StringReplace

StringReplace["string",ssp]

replaces the string expression s by sp wherever it appears in "string".

StringReplace["string",{s1sp1,s2sp2,}]

replaces the string expressions si by spi whenever they appear as substrings of "string".

StringReplace["string",srules,n]

does only the first n replacements.

StringReplace[{s1,s2,},srules]

gives the list of results for each of the si.

StringReplace[srules]

represents an operator form of StringReplace that can be applied to an expression.

Details and Options

  • The string expressions si can contain any of the objects specified in the notes for StringExpression.
  • StringReplace goes through a string, testing substrings that start at each successive character position. On each substring, it tries in turn each of the transformation rules you have specified. If any of the rules apply, it replaces the substring, then continues to go through the string, starting at the character position after the end of the substring.
  • If the spi in the replacements si->spi do not evaluate to strings, StringReplace will yield a StringExpression rather than an ordinary string.
  • In replacements of the form si:>spi, the spi are not evaluated until each time they are used.
  • Setting the option IgnoreCase->True makes StringReplace treat lowercase and uppercase letters as equivalent.
  • StringReplace[srules][expr] is equivalent to StringReplace[expr,srules].

Examples

open allclose all

Basic Examples  (3)

Replace every occurrence of "ab" with "X":

In[1]:=
Click for copyable input
Out[1]=

Replace every substring that has one or more occurrences of "ab" with "X":

In[1]:=
Click for copyable input
Out[1]=

Use the operator form of StringReplace:

In[1]:=
Click for copyable input
Out[1]=

Scope  (9)

Generalizations & Extensions  (1)

Options  (1)

Applications  (7)

Properties & Relations  (1)

Neat Examples  (1)

See Also

Replace  StringReplaceList  StringReplacePart  StringDelete  StringPosition  StringTrim  StringSplit  StringTemplate  ToLowerCase  ToUpperCase  RemoveDiacritics  Pluralize  SubstitutionSystem

Tutorials

Introduced in 1991
(2.0)
| Updated in 2016
(10.4)