如何在 MATLAB 中将此字符串解析为元胞数组?

How can I parse this string into a cell array in MATLAB?

我有一个字符串:

sen = '0.31431 0.64431 Using drugs is not cool Speaker2';

我正在尝试编写将生成的代码:

cell = {'0.31431','0.64431', 'Using drugs is not cool', 'Speaker2'};

问题是我不想使用 'Using drugs is not cool' 中的字数,因为这些在其他示例中会发生变化。

我试过了:

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

但效果不理想。

如果您知道您总是需要删除前两个词和最后一个词,将所有其他词收集在一起,那么您可以按如下方式使用 strsplit and strjoin

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'

你可以使用正则表达式,但它有点难看:

>> 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'}