function s = extract(str, pat)
% EXTRACT Extract matched substrings
%    S = EXTRACT(STR, PAT_STR) returns all occurrences where PAT_STR is 
%    found in STR.
%
%    S = EXTRACT(STR, PAT_POS) returns the character found at PAT_POS.
%
%    S = EXTRACT(STR, PAT_PAT) returns all occurrences where the 
%    pattern array PAT_PAT is found in STR.
%
%    STR and PAT_STR must be a string array, a character vector, or a cell
%    array of character vectors. If STR is a string then the output S will
%    be a string, otherwise, S is a cell array of character vectors.
%
%    Examples:
%        STR = "The quick brown fox";
%        PAT = 'brown';
%        extract(STR,PAT)
%
%        % returns "brown"
%
%        STR = 'peppers and onions';
%        PAT = 6;
%        extract(STR,PAT)
%
%        % returns {'r'}
%
%        STR = "The answer is either 24 or 42!";
%        PAT = digitsPattern;
%        extract(STR, PAT)
%
%        % returns ["24";"42"]
%
%    See also EXTRACTAFTER, EXTRACTBEFORE, EXTRACTBETWEEN, PATTERN, DIGITSPATTERN

%   Copyright 2016-2020 The MathWorks, Inc.

    narginchk(2, 2);
    if ~isTextStrict(str)
        firstInput = getString(message('MATLAB:string:FirstInput'));
        error(message('MATLAB:string:MustBeCharCellArrayOrString', firstInput));
    end

    try
        s = string(str);
        s = s.extract(pat);

        if ~isstring(str)
            s = cellstr(s);
        end
        
    catch E
        throw(E);
    end
end

function tf = isTextStrict(value)
    tf = (ischar(value) && ((isempty(value) && isequal(size(value),[0 0])) || isrow(value))) || isstring(value) || iscellstr(value);
end

