1

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?

Community
  • 1
  • 1
rob
  • 6,147
  • 2
  • 37
  • 56

1 Answers1

2

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'))
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • I forgot about `any`! I figured there had to be something at least a little simpler than wrapping it all in `~isempty(find())`. Thanks. Oops, I guess I goofed and my regex should have been `^-?foo$` so the concatenation won't work in my case...but maybe it'll be helpful for someone else. Thanks again for the quick & thorough answer. – rob Oct 25 '13 at 18:36