Search code examples
regexstringmatlabcell-array

How to find a substring in a cell array


I am trying to use regexp in MATLAB to search for two words in strings in cell arrays. My cell array contains

strings={'1abc_2def_ghi_AB_12A','1abc_2def_ghi_BD_19A','1abc_2def_ghi_CD_16A',}

How would I go about constructing the expression to search the cell array for the string that contains both 'ghi' and '12'?

Thanks in advance for any assistance.


Solution

  • How about this?

    result = find(~cellfun(@isempty, regexp(strings, 'ghi')) & ...
        ~cellfun(@isempty, regexp(strings, 'AB')));
    

    Or, using a single regular expression,

    result = find(~cellfun(@isempty, regexp(strings, '(ghi.*AB|ghi.*AB)')));