Simplify regexprep to avoid having to use a loop

1 次查看(过去 30 天)
Hi,
I have a list of Identifiers representing a hierarchy that I need to change slightly in order to process them. The Identifiers are use '_' in order to separate hierarchy levels. What I want to do is to replace all '_' from the 3rd '_' onwards.
I was able to find the regexprep code, but I am only able to replace one '_' at the time and then using a loop. The code I was able to come up with looks as follows:
clear;clc;
nodes ={'RB_AA_AL_CTA'; 'RB_AA_AL_HDGE'; 'RB_AA_CA'; 'RB_AA_EH'; 'RB_AA_EQ_DMLC_EUR'; 'RB_AA_EQ_DMLC_USD'; 'RB_AA_EQ_DMLC_JPY';};
for x=1:length(nodes)
for y = 2: length(cell2mat(strfind(nodes(x),'_')))
nodes(x) = regexprep(nodes(x),'_','-',3);
end
end
I am wondering now whether it is possible to simplify this such that I don't have to use a loop? Thanks Sven

采纳的回答

per isakson
per isakson 2015-4-1
编辑:per isakson 2015-4-1
At least different
for jj = 1:length(nodes)
ix_ = find(nodes{jj}=='_');
if length(ix_) >= 3
nodes{jj}(ix_(3):end) = strrep(nodes{jj}(ix_(3):end), '_', '-' );
end
end
however, slower :(
&nbsp
This is better
for jj = 1:length(nodes)
ix_ = find(nodes{jj}=='_');
if length(ix_) >= 3
nodes{jj}(ix_(3:end)) = '-';
end
end

更多回答(1 个)

SpeedyGonzales
SpeedyGonzales 2015-4-1
Thank you! This is helpful...

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by