Find and replace substring
modifiedStr
=
strrep(origStr
, oldSubstr
, newSubstr
)
replaces
all occurrences of modifiedStr
=
strrep(origStr
, oldSubstr
, newSubstr
)oldSubstr
within origStr
with 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'; ... 'c:\calories.m'}; d_files = strrep(c_files, 'c:', 'd:')
MATLAB returns:
d_files = 'd:\cookies.m' 'd:\candy.m' 'd:\calories.m'
Replace text in a cell array with values in a second cell array:
missing_info = {'Start: __'; ... 'End: __'}; dates = {'01/01/2001'; ... '12/12/2002'}; 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 character vector
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 **