MATLAB: Replace multiple characters in a string with different characters

multiple replacementregexprep

Hello! I am trying to replace multiple characters in a string using only one line of command. I am aware I can use regexprep to replace multiple characters with a single character like:
line = 'I am ready to use MATLAB';
replaced = regexprep(line,'[ru]','!');
this will give me: 'I am !eady to !se MATLAB'. But I want to replace the 'r' with a '!' and 'u' with '%'. So that the output will be like:
'I am !eady to %se MATLAB'
I do not want to use strrep for each replacement. How can I go about it? Thanks!

Best Answer

Are you sure you don't want to use strrep?
strrep(strrep(line, 'r', '!'), 'u', '%')
I like to avoid the regexp functions if possible since there's a lot of sanity checks that goes on in those function, adding to delay. If its a simple 1-time call, then regexprep works fine.
line = 'I am ready to use MATLAB';
tic
for j = 1:100000
regexprep(line,{'r','u'},{'!','%'});
end
t1 = toc %0.683225 seconds
tic
for j = 1:100000
strrep(strrep(line, 'r', '!'), 'u', '%');
end
t2 = toc %0.215329 seconds