Find cell containing part of a string

14 次查看(过去 30 天)
I would like to find the elements of a cell array that contain part of a specified string.
colorList = {'Red', 'Green', 'Blue', 'Purple'}; % List of values to match with
stringToCheck = 'Blue 23948723'; % String we are trying to match
I would like to return index=3 of colorList since that entry contains the stringToCheck text of 'Blue'. How can I do this?

采纳的回答

Cedric
Cedric 2017-10-26
编辑:Cedric 2017-10-26
If you cannot assume that keywords are separated by white spaces:
>> find(cellfun(@(x)~isempty(strfind(stringToCheck,x)), colorList))
ans =
3
  2 个评论
KAE
KAE 2017-10-26
编辑:KAE 2017-10-26
They may not be, I hadn't thought of that so thanks.

请先登录,再进行评论。

更多回答(2 个)

per isakson
per isakson 2017-10-26
编辑:per isakson 2017-10-26
>> find( ismember( colorList, strsplit( stringToCheck ) ) )
ans =
3
or
>> find( ismember( colorList, strsplit( stringToCheck, {'\s','\.',','} ...
, 'CollapseDelimiters',true, 'DelimiterType','RegularExpression' ) ) )
ans =
3
if the color name is followed by a period or comma, e.g. "Blue.". And what about upper and lower case, e.g "blue"? And "Bluetooth"?

Akira Agata
Akira Agata 2017-10-26
If your MATLAB is R2016b or later version, you can use contains function, like:
idx = cellfun(@(x) contains(stringToCheck,x),colorList);
The answer is:
>> colorList(idx)
ans =
{'Blue'}
  1 个评论
KAE
KAE 2017-10-27
Thank you, this syntax is easier to read and thus remember than then other ones.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by