stringmatlab

contains with separate result for each of multiple patterns


Matlab's documentation for the function TF = contains(str,pattern) states:

If pattern is an array containing multiple patterns, then contains returns 1 if it finds any element of pattern in str.

I want a result for each pattern individually however. That is:

I have string A='a very long string' and two patterns B='very' and C='long'. I want to check if B is contained in A and if C is contained in A. I could do it like this:

result = false(2,1);
result(1) = contains(A,B);
result(2) = contains(A,C);

but for many patterns this takes quite a while. What is the fast way to do this?


Solution

  • I don't know or have access to that function; it must be "new", so I don't know its particular idiosyncrasies.

    How I would do that is:

    result = ~cellfun('isempty', regexp(A, {B C}));
    

    EIDT

    Judging from the documentation, you can do the exact same thing with contains:

    result = contains(A, {B C});
    

    except that seems to return contains(A,B) || contains(A,C) rather than the array [contains(A,B) contains(A,C)]. So I don't know, I can't test it here. But if all else fails, you can use the regex solution above.