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

20 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 10 Jan 2018
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';

More Answers (1)

Walter Roberson
Walter Roberson on 10 Jan 2018
pattern = '^(?[^;]*;){4}';
extractResults = regexprep(CellArrayS, pattern, '', 'lineanchors')
  1 Comment
Cecile
Cecile on 10 Jan 2018
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.

Sign in to comment.

Categories

Find more on Data Import and Export in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!