Find cell containing part of a string

조회 수: 14 (최근 30일)
KAE
KAE 2017년 10월 26일
댓글: KAE 2017년 10월 27일
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.
Cedric
Cedric 2017년 10월 26일
My pleasure!

댓글을 달려면 로그인하십시오.

추가 답변 (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"?
  댓글 수: 1
KAE
KAE 2017년 10월 26일
Thank you, this works and your scenarios are useful too.

댓글을 달려면 로그인하십시오.


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