Find index of pattern match

17 次查看(过去 30 天)
Hello! I am trying to find index position of a pattern from a string array in a string. for example:
string='Mary had a little lamb';
fcnset=["big","little","small"];
I would want the result as the index of 'little' from the string. I tried the following line, but it doesn't work:
n = find(contains(string,fcnset));
how do I go about it?

采纳的回答

Stephen23
Stephen23 2018-8-13
编辑:Stephen23 2018-8-13
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> idx = ~cellfun('isempty',strfind(str,pat))
idx =
0 1 0
>> find(idx)
ans = 2
  2 个评论
Tiasa Ghosh
Tiasa Ghosh 2018-8-13
I get the following error on running the same code
Stephen23
Stephen23 2018-8-13
编辑:Stephen23 2018-8-13
Aaah, sorry. Try one of these:
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> idx = ~cellfun('isempty',regexp(str,pat))
idx =
0 1 0
>> find(idx)
ans = 2
Or
>> str = 'Mary had a little lamb';
>> pat = {'big','little','small'};
>> fun = @(p)isempty(strfind(str,p));
>> idx = ~cellfun(fun,pat)
idx =
0 1 0
>> find(idx)
ans = 2
Or
contains

请先登录,再进行评论。

更多回答(1 个)

KSSV
KSSV 2018-8-13
编辑:KSSV 2018-8-13
string='Mary had a little lamb';
fcnset=["big","little","small"];
idx = zeros(3,1) ;
for i = 1:3
idx(i) = contains(string,fcnset{i}) ;
end

类别

Help CenterFile Exchange 中查找有关 Linear Regression 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by