[英]MATLAB find cell array substrings in a cell array of strings
假設我們有一個子字符串arrayOfSubstrings = {substr1;substr2}
的單元格數組和一個字符串arrayOfStrings = {string1;string2;string3;stirng4}
arrayOfSubstrings = {substr1;substr2}
的單元格數組。 我如何才能將邏輯映射映射到找到至少一個子字符串的字符串的單元格數組中? 我努力了
cellfun('isempty',regexp(arrayOfSubstrings ,arrayOfStrings ))
和
cellfun('isempty', strfind(arrayOfSubstrings , arrayOfStrings ))
以及其他一些功能上的排列,但是卻一無所獲。
問題在於,使用strfind
和regexp
,您不能提供兩個單元格數組並使它們自動將所有模式應用於所有字符串。 您將需要遍歷一個或另一個來使其正常工作。
您可以使用顯式循環來執行此操作
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
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
如果您使用的是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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.