New string based on parts of old string

2 ビュー (過去 30 日間)
DavidL88
DavidL88 2021 年 12 月 14 日
コメント済み: DavidL88 2021 年 12 月 14 日
How do I get new str from this old string? All the strings are in this format. Is there a way to extract based on the position from '(' and after '|'?
OldStr1 = 'Extract clusters: PR (2 files) | DG_MD_CG_22'
OldStr2 = 'Extract clusters: OR (2 files) | AG_MD_HH_CG_HH_22'
NewStr1 = 'DG_MD_CG_22_PR'
NewStr2 = 'AG_MD_HH_CG_HH_22_OR'

採用された回答

Voss
Voss 2021 年 12 月 14 日
OldStr1 = 'Extract clusters: PR (2 files) | DG_MD_CG_22';
OldStr2 = 'Extract clusters: OR (2 files) | AG_MD_HH_CG_HH_22';
NewStr1 = construct_new_str(OldStr1)
NewStr1 = 'DG_MD_CG_22_PR'
NewStr2 = construct_new_str(OldStr2)
NewStr2 = 'AG_MD_HH_CG_HH_22_OR'
function new_str = construct_new_str(str)
idx0 = find(str == ':',1,'last');
idx1 = find(str == '(',1,'last');
idx2 = find(str == '|',1,'last');
new_str = [str(idx2+2:end) '_' str(idx0+2:idx1-2)];
end
  1 件のコメント
DavidL88
DavidL88 2021 年 12 月 14 日
Thanks

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2021 年 12 月 14 日
I would use the extract* functions listed in the Join and Split section of the Characters and Strings category page in the documentation.
s = 'hocus pocus'
s = 'hocus pocus'
h = extractBefore(s, ' ')
h = 'hocus'
p = extractAfter(s, ' ')
p = 'pocus'
  1 件のコメント
DavidL88
DavidL88 2021 年 12 月 14 日
Thanks

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

カテゴリ

Help Center および File ExchangeString Parsing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by