Find index of pattern match

35 vues (au cours des 30 derniers jours)
Tiasa Ghosh
Tiasa Ghosh le 13 Août 2018
Modifié(e) : Stephen23 le 13 Août 2018
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?

Réponse acceptée

Stephen23
Stephen23 le 13 Août 2018
Modifié(e) : Stephen23 le 13 Août 2018
>> 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 commentaires
Tiasa Ghosh
Tiasa Ghosh le 13 Août 2018
I get the following error on running the same code
Stephen23
Stephen23 le 13 Août 2018
Modifié(e) : Stephen23 le 13 Août 2018
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

Connectez-vous pour commenter.

Plus de réponses (1)

KSSV
KSSV le 13 Août 2018
Modifié(e) : KSSV le 13 Août 2018
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
  1 commentaire
Tiasa Ghosh
Tiasa Ghosh le 13 Août 2018
Thank you for your input!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by