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

10 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Stephen23
Stephen23 il 10 Gen 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';

Più risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by