MATLAB: Counting occurance of exact word from string array

countexact matchMATLABoccurancestring

Hi,
I am having trouble counting how many times a certain word appears in a string. I need to count the 'exact match' only, ignoring substrings. I tried 'count' and some other options but couldn't figure this out. The strings are chemical equations and the words are chemical species. Here's an example:
R1 = ["Ar* + Ar* "," Ar+ + Ar + e "]; % chemical reaction (string array; col1=reactants, col2=products)
S = {'Ar';'Ar*';'Ar+';'e'}; % species (cell array)
I want to get two variables as a result (below).
NumR = [0, 2, 0, 0]; % Number of occurance of each species as reactants
NumP = [1, 0, 1, 1]; % Number of occurance of each species as products
% each column represent number of occurance of Ar, Ar*, Ar+, e respectively
I tried 'count' function but this gives me a wrong result. For instance, if I try to count the number of occurance of 'Ar', Matlab also counts 'Ar+' and 'Ar*' as 'Ar' even though they are different species. How do I ignore substrings (i.e. 'Ar+' and 'Ar*' in this case)?
Thank you!

Best Answer

>> C = {'Ar* + Ar* ',' Ar+ + Ar + e '};
>> S = {'Ar';'Ar*';'Ar+';'e'};
>> rgx = strcat('(?<=\s|^)',regexptranslate('escape',S),'(?=\s|$)');
>> NumR = cellfun(@numel,regexp(C{1},rgx))
NumR =
0
2
0
0
>> NumP = cellfun(@numel,regexp(C{2},rgx))
NumP =
1
0
1
1