String 如何在MATLAB中将该字符串解析为单元格数组?

String 如何在MATLAB中将该字符串解析为单元格数组?,string,matlab,split,string-formatting,cell-array,String,Matlab,Split,String Formatting,Cell Array,我有一个字符串: sen = '0.31431 0.64431 Using drugs is not cool Speaker2'; 我正在尝试编写代码,以生成: cell = {'0.31431','0.64431', 'Using drugs is not cool', 'Speaker2'}; 问题是我不想在“吸毒不酷”中使用字数,因为在其他示例中这些字数会发生变化 我试过: output = sscanf(sen,'%s %s %c %Speaker%d'); 但是它并没有按预

我有一个字符串:

sen = '0.31431 0.64431 Using drugs is not cool Speaker2';
我正在尝试编写代码,以生成:

cell = {'0.31431','0.64431', 'Using drugs is not cool', 'Speaker2'};
问题是我不想在
“吸毒不酷”
中使用字数,因为在其他示例中这些字数会发生变化

我试过:

output = sscanf(sen,'%s %s %c %Speaker%d');  

但是它并没有按预期的那样工作。

如果您知道您将始终需要删除前两个单词和最后一个单词,并将所有其他单词收集在一起,那么您可以使用and,如下所示:

sen = '0.31431 0.64431 Using drugs is not cool Speaker2';
words = strsplit(sen);  % Split all words up
words = [words(1:2) {strjoin(words(3:end-1), ' ')} words(end)]  % Join words 3 to end-1

words =

  1×4 cell array

    '0.31431'    '0.64431'    'Using drugs is not cool'    'Speaker2'

您可以使用regexp,但它有点难看:

>> str = '0.31431 0.64431 Using drugs is not cool Speaker2';
>> regexp(str,'(\d+\.\d+)\s(\d+\.\d+)\s(.*?)\s(Speaker\d+)','tokens')

ans =

  1×1 cell array

    {1×4 cell}

>> ans{:}

ans =

  1×4 cell array

    {'0.31431'}    {'0.64431'}    {'Using drugs is not cool'}    {'Speaker2'}