MATLAB在字符串的单元格数组中查找单元格数组子字符串 [英] MATLAB find cell array substrings in a cell array of strings

查看:175
本文介绍了MATLAB在字符串的单元格数组中查找单元格数组子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个子字符串arrayOfSubstrings = {substr1;substr2}的单元格数组和一个字符串arrayOfStrings = {string1;string2;string3;stirng4}的单元格数组.如何才能将逻辑映射映射到找到至少一个子字符串的字符串的单元格数组中?我尝试过

Let's say we have a cell array of substrings arrayOfSubstrings = {substr1;substr2} and a cell array of strings arrayOfStrings = {string1;string2;string3;stirng4}. How can I get a logical map into the cell array of strings where at least one of the substrings is found? I have tried

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

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

和其他一些功能排列,但没有得到实现.

and some other permutations of functions, but am not getting anywhere.

推荐答案

问题在于,同时使用strfindregexp时,您无法提供两个单元格数组并使它们自动将所有模式应用于所有字符串.您将需要遍历一个或多个来使其正常工作.

The issue is that with both strfind and regexp is that you can't provide two cell arrays and have them automatically apply all patterns to all strings. You will need to loop through one or the other to make it work.

您可以通过显式循环进行操作

You can do this with an explicit loop

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

Or if you are for loop-averse you can use cellfun

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

一种不同的方法

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

A Different Approach

Alternately, you could combine your sub-strings into a single regular expression

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

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

这篇关于MATLAB在字符串的单元格数组中查找单元格数组子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆