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!