Simplify regexprep to avoid having to use a loop

1 回表示 (過去 30 日間)
SpeedyGonzales
SpeedyGonzales 2015 年 3 月 31 日
回答済み: SpeedyGonzales 2015 年 4 月 1 日
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...

サインインしてコメントする。

その他の回答 (1 件)

SpeedyGonzales
SpeedyGonzales 2015 年 4 月 1 日
Thank you! This is helpful...

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by