简体   繁体   English

Matlab拆分字符串多个分隔符

[英]Matlab split string multiple delimiters

I have a cell list of strings like this: 我有一个像这样的字符串单元格列表:

cellArr = 
      'folderName_fileName_no.jpg',
      'folderName2_fileName2_no2.jpg'

I want to get it like this 我希望得到这样的

{folderName, fileName, no},
{folderName2, fileName2, no2}

How to do it in matlab? 怎么在matlab中做到? I know I can use 我知道我可以使用

regexp(cellArr, '_', 'split'), 

but how can I use more than one delimiters? 但是我怎样才能使用多个分隔符呢?

我找到了..谢谢你的回复..

regexp(cellArr, '[_.]', 'split')

It is very similar to the C method of string tokenization. 它与字符串标记化的C方法非常相似。 Using strtok , you can tokenize based on whichever delimiter you choose ( in your case '_' ) 使用strtok ,您可以根据您选择的分隔符进行标记(在您的情况下为'_')

STRTOK reference STRTOK参考

Note, you will use the C idiom of repeatedly calling strtok in a loop on its remaining string as it returns only the first token each time. 注意,你将使用在其剩余字符串的循环中重复调用strtok的C语言,因为它每次只返回第一个标记。 An example is given in the reference. 参考文献中给出了一个例子。

To answer your EDIT: 要回答你的编辑:

Using strtok on a cell array of strings returns a cell array of strings in token and a character array in remain: 在字符串的单元格数组上使用strtok会返回令牌中的字符串单元格数组以及仍然存在的字符数组:

s = {'all in good time'; ...
 'my dog has fleas'; ...
 'leave no stone unturned'};

remain = s;

for k = 1:4
   [token, remain] = strtok(remain);
   token
end

straight from example 3 in the reference. 直接来自参考文献中的例子3。 < To make it quite obvious, you just replace strtok(remain) with strtok(remain,REQUIRED_DELIMITERS) and add trivial logic to drop the file extension. <为了说明这一点,你只需用strtok(remain)替换strtok(remain) strtok(remain,REQUIRED_DELIMITERS)并添加简单的逻辑来删除文件扩展名。

It also useful to do using strsplit : 使用strsplit也很有用:

cellArr = 
      'folderName_fileName_no.jpg',
      'folderName2_fileName2_no2.jpg'

C = strsplit(cellArr,'_')

Then C is a cell array containing the three vectors. 然后C是包含三个向量的单元阵列。 Also there is filepath if it's needed to remove parts not necessary, like extensions. 还有文件filepath如果需要删除不必要的部分,如扩展。 strsplit can also be used with Regex if it needs to! 如果需要, strsplit也可以与Regex一起使用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM