Extracting part of a string after the nth occurrence of a character

20 ビュー (過去 30 日間)
Cecile
Cecile 2018 年 1 月 10 日
コメント済み: Cecile 2018 年 1 月 11 日
Hello,
I have a cell array of string which looks like this:
cellArrayS = {'staticString1;staticString2;staticString3;1;nextString'; ... 'staticString1;staticString2;staticString3;2;nextString;nextString'; ... 'staticString1;staticString2;staticString3;3;nextString;nextString;nextString'; ... 'staticString1;staticString2;staticString3;4;nextString;;;;'; ... 'staticString1;staticString2;staticString3;5;nextString;nextString'};
I would like to extract all the characters after the 4th semi-column until the end of the string. The results would be as follow:
extractResults =
'nextString';
'nextString'; 'nextString';
'nextString'; 'nextString'; 'nextString';
'nextString';;;;
'nextString'; 'nextString';
I have tried looking at related example on this question, playing around with regexp, find and extractAfter but I didn’t manage to get anywhere.
Thank you very much.
Cecile

採用された回答

Stephen23
Stephen23 2018 年 1 月 10 日
C = {...
'staticString1'';''staticString2'';''staticString3'';1;''nextString'';'
'staticString1'';''staticString2'';''staticString3'';2;''nextString'';''nextString'';'
'staticString1'';''staticString2'';''staticString3'';3;''nextString'';''nextString'';''nextString'';'
'staticString1'';''staticString2'';''staticString3'';4;''nextString'';;;;'
'staticString1'';''staticString2'';''staticString3'';5;''nextString'';''nextString'';'
};
T = regexp(C,'^(([^;]+;){4})(.*)$','once','tokens');
Z = cellfun(@(c)c{end},T,'uni',0);
giving:
>> Z{:}
ans = 'nextString';
ans = 'nextString';'nextString';
ans = 'nextString';'nextString';'nextString';
ans = 'nextString';;;;
ans = 'nextString';'nextString';
  1 件のコメント
Cecile
Cecile 2018 年 1 月 11 日
Thank you very much, it works perfectly.

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 1 月 10 日
pattern = '^(?[^;]*;){4}';
extractResults = regexprep(CellArrayS, pattern, '', 'lineanchors')
  1 件のコメント
Cecile
Cecile 2018 年 1 月 10 日
Thank you very much Walter. extractResults looks exactly like the original cellArrayS when I try your example above. I guess the pattern regular expresion needs to be edited? I am not able to read it unfortunately to see where the issue is. Would you be able to take another look? Thank you very much.

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

カテゴリ

Help Center および File ExchangeData Import and Export についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by