Find and replace substring


modifiedStr = strrep(origStr, oldSubstr, newSubstr)


modifiedStr = strrep(origStr, oldSubstr, newSubstr) replaces all occurrences of the string oldSubstr within string origStr with the string newSubstr.


Replace text in a character array:

claim = 'This is a good example.';
new_claim = strrep(claim, 'good', 'great')

MATLAB® returns:

new_claim =
This is a great example.

Replace text in a cell array:

c_files = {'c:\cookies.m'; ...
           'c:\candy.m';   ...
d_files = strrep(c_files, 'c:', 'd:')

MATLAB returns:

d_files = 

Replace text in a cell array with values in a second cell array:

missing_info = {'Start: __'; ...
                'End: __'};

dates = {'01/01/2001'; ...

complete = strrep(missing_info, '__', dates)

MATLAB returns:

complete = 
    'Start: 01/01/2001'
    'End: 12/12/2002'

Compare the use of strrep and regexprep to replace a string with a repeated pattern:

repeats = 'abc 2 def 22 ghi 222 jkl 2222';
indices = strfind(repeats, '22')

using_strrep = strrep(repeats, '22', '*')
using_regexprep = regexprep(repeats, '22', '*')

MATLAB returns:

indices =
    11    18    19    26    27    28

using_strrep =
abc 2 def * ghi ** jkl ***

using_regexprep =
abc 2 def * ghi *2 jkl **

More About

expand all


  • strrep accepts input combinations of single strings, strings in scalar cells, and same-sized cell arrays of strings. If any inputs are cell arrays, strrep returns a cell array.

  • The strrep function does not find empty strings for replacement. That is, when origStr and oldSubstr both contain the empty string (''), strrep does not replace '' with the contents of newSubstr.

  • Before replacing strings, strrep finds all instances of oldSubstr in origStr, like the strfind function. For overlapping patterns, strrep performs multiple replacements. See the final example in the Examples section.

See Also


Introduced before R2006a

Was this topic helpful?