Search code examples
regexmatlabcell-array

Simplest way to find out if at least one cell in a cell array matches a regular expression


I need to search a cell array and return a single boolean value indicating whether any cell matches a regular expression.

For example, suppose I want to find out if the cell array strs contains foo or -foo (case-insensitive). The regular expression I need to pass to regexpi is ^-?foo$.

Sample inputs:

strs={'a','b'} % result is 0

strs={'a','foo'} % result is 1

strs={'a','-FOO'} % result is 1

strs={'a','food'} % result is 0

I came up with the following solution based on How can I implement wildcard at ismember function of matlab? and Searching cell array with regex, but it seems like I should be able to simplify it:

~isempty(find(~cellfun('isempty', regexpi(strs, '^-?foo$'))))

The problem I have is that it looks rather cryptic for such a simple operation. Is there a simpler, more human-readable expression I can use to achieve the same result?


Solution

  • NOTE: The answer refers to the original regexp in the question: '-?foo'

    You can avoid the find:

    any(~cellfun('isempty', regexpi(strs, '-?foo')))
    

    Another possibility: concatenate first all cells into a single string:

    ~isempty(regexpi([strs{:}], '-?foo'))
    

    Note that you can remove the "-" sign in any of the above:

    any(~cellfun('isempty', regexpi(strs, 'foo')))
    
    ~isempty(regexpi([strs{:}], 'foo'))
    

    And that allows using strfind (with lower) instead of regexpi:

    ~isempty(strfind(lower([strs{:}]),'foo'))