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

10 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Stephen23
Stephen23 el 10 de En. de 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';

Más respuestas (1)

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

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by