MATLAB在字符串的单元格数组中查找单元格数组子字符串

时间:2017-03-29 14:54:13

标签: arrays string matlab

我们假设我们有一个子串arrayOfSubstrings = {substr1;substr2}的单元格数组和一个字符串arrayOfStrings = {string1;string2;string3;stirng4}的单元格数组。如何在字符串的单元格数组中获取逻辑映射,其中至少找到一个子字符串?我试过了

cellfun('isempty',regexp(arrayOfSubstrings ,arrayOfStrings ))

cellfun('isempty', strfind(arrayOfSubstrings , arrayOfStrings ))

和其他一些功能的排列,但我没有到达任何地方。

2 个答案:

答案 0 :(得分:3)

问题在于,strfindregexp都是您无法提供两个单元格数组并让它们自动将所有模式应用于所有字符串。您需要循环使用其中一个才能使其正常工作。

您可以使用显式循环

执行此操作
strings = {'ab', 'bc', 'de', 'fa'};
substrs = {'a', 'b', 'c'};

% First you'll want to escape the regular expressions
substrs = regexptranslate('escape', substrs);

matches = false(size(strings));

for k = 1:numel(strings)
    matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs)));
end

% 1  1  0  1

或者,如果你是厌恶循环,你可以使用cellfun

cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings)
% 1  1  0  1

不同的方法

或者,您可以将子字符串组合成单个正则表达式

pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
%   (a|b|c)

output = ~cellfun('isempty', regexp(strings, pattern));
%   1  1  0  1

答案 1 :(得分:1)

如果您使用的是R2016b或R2017a,则可以使用contains:

>> strings = {'ab', 'bc', 'de', 'fa'};
>> substrs = {'a', 'b', 'c'};
>> contains(strings, substrs)

ans =

  1×4 logical array

   1   1   0   1

包含也是最快的,特别是如果您使用新的字符串数据类型。

function profFunc()

    strings = {'ab', 'bc', 'de', 'fa'};
    substrs = {'a', 'b', 'c'};

    n = 10000;

    tic;
    for i = 1:n
        substrs_translated = regexptranslate('escape', substrs);

        matches = false(size(strings));

        for k = 1:numel(strings)
            matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs_translated)));
        end
    end
    toc

    tic;
    for i = 1:n
        cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings);
    end
    toc

    tic;
    for i = 1:n
        pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
        output = ~cellfun('isempty', regexp(strings, pattern)); %#ok<NASGU>
    end
    toc

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc

    %Imagine you were using strings for all your text!
    strings = string(strings);

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc
end

计时结果:

>> profFunc
Elapsed time is 0.643176 seconds.
Elapsed time is 1.007309 seconds.
Elapsed time is 0.683643 seconds.
Elapsed time is 0.050663 seconds.
Elapsed time is 0.008177 seconds.