MATLAB: Problems finding exact match for a string

exactmatchproblemregexpregexpistringsubstring

Hello,
I would like to match a string in a list of other strings (cell array). My problem is that in using regexpi or regexp, it misidentifies the location of the string if it finds it as a substring. For example
GN= {‘EC2020’}; In looking at a cell array of strings, GN will be found in the string ‘EC2020.1’
I do not want it to match with this expression because this is string stands for something different. I simply want to exact match EC2020 without including EC2020.1 as a hit. Some more details of this is example:
GN = {'EC2020'};
List = {'EC1919'; 'EC2020'; 'EC2020.1'};
dList = length(List(:,1));
pds = cell(1,dL);
j = 1;
for i = 1:dList
c = find(~cellfun(@isempty,regexpi(List(i,:),GN)));
if ~isempty(c)
pds(j)= List(i,1);
j = j + 1;
end
end
Any help would be greatly appreciated!

Best Answer

What about strcmp:
GN = {'EC2020'};
List = {'EC1919'; 'EC2020'; 'EC2020.1'};
index = find(strcmp(List, GN{1}))
any(strcmp(List, GN{1})) looks much easier than
~isempty(find(~cellfun(@isempty,regexpi(List(i,:),GN))))
Your output pds is a cell of the same size as List, and it contains the searched strings as often, as they are found. This can be done without a loop by:
pds = List(strcmp(List, GN{1}));
Notes:
  • length(List(:,1)) wastes time with creating the vector List(:,1). Prefer: size(List, 1)
  • cellfun('isempty', ...) is faster than |cellfun(@isempty, ...)