replace multiple characters in a string with different characters
106 ビュー (過去 30 日間)
古いコメントを表示
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!
採用された回答
OCDER
2018 年 7 月 9 日
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
その他の回答 (2 件)
Rik
2018 年 7 月 9 日
You can enter cellstring inputs:
>>line = 'I am ready to use MATLAB';
>>replaced = regexprep(line,{'r','u'},{'!','%'});
replaced =
'I am !eady to %se MATLAB'
Rik
2018 年 7 月 9 日
編集済み: Rik
2018 年 7 月 9 日
If you want to follow OCDER's advice, I would go for option 3. Using strrep in a loop is of course slower, but it allows much more flexibility in the number of replacements, and it is arguably more readable. (a lot of the extra time is spent in the call to numel)
line = 'I am ready to use MATLAB';
tic
for j = 1:100000
regexprep(line,{'r','u'},{'!','%'});
end
t1 = toc %0.8180 seconds
tic
for j = 1:100000
strrep(strrep(line, 'r', '!'), 'u', '%');
end
t2 = toc %0.2253 seconds
old={'r','u'};new={'!','%'};
tic
for j = 1:100000
for k=1:numel(old)
strrep(line, old{k}, new{k});
%line=strrep(line, old{k}, new{k});
end
end
t3 = toc %0.3066 seconds (0.2789 seconds with k=1:2)
参考
カテゴリ
Help Center および File Exchange で Get Started with MATLAB についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!