MATLAB: How to use metacharacters in combination with cell arrays to build up a pattern for regexp

metacharactersregexp

I just started coding, and I can't manage regexp properly and I guess my codes are not that efficient, but here is what I would need:
I wrote a code like this, where X and Y are both cell arrays (where every cell consists of string arrays).
Y{1} is defined.
for i=1:length(X)
for k=1:length(Y{i})
Z{i}(k+1)=max(find(~cellfun(@isempty,regexp(X{i}, Y{i}{k}))));
...
end
end
This works fine cause I expect Z to be a cell array of indices, indices of max position of occurence of the string contained in Y{i}{k}.
The problem is that this string (let's say for example "22") is contained also in other strings within Y{i}{k} (let's say "3422"), but my goal is to get the max index of occurence of the string "22" with no other digits or characters before or after it.
What I ask now is a method, possibly using metacharacters, to get the max index of occurence of just the string Y{i}{k} with no digits or characters behind or after.
I thought of using something like –> '(?<!\d)(\d)(?!\d)' matches single-digit numbers (digits that do not precede or follow other digits),
but it seems hard to match metacharacters and Y{i}{k} in the same pattern. I got a snapshot below of what I attempted with no success, it might help.
Any idea of how to solve this? Thanks in advance!!

Best Answer

"my goal is to get the max index of occurence of the string "22" with no other digits or characters before or after it."
I assume for now that by "no characters" you actually mean no non-whitespace characters, or perhaps no letter characters. Clarification would be helpful on this..
Possibly a good appraoch would be to use anchors:
and you can trivially join these with the Y string either concatenation or sprintf, e.g.:
rgx = sprintf('\\<%s\\>',Y{i}{k});
regex(X{i},rgx)
Most likely you can remove on of the loops by constructing one regular expression for all of the k strings, e.g.:
rgx = '\<(22|23|99|123)\>';
You can gemerate that quite easily using sprintf or strjoin or similar.
"No Characters": your description that you want "no other digits or characters before or after it" literally means that you would only match this string "22", because whitespace , ounctuation, and non-printing characters are also characters, so by your description must be excluded... leaving literally no characters.
I assumed above that you actually mean to match the substring
"... 22 ..."
% ^ ^ whitespace, not letter, not digit
Are punctuation characters allowed or not? If you really do mean "no characters" then using regular expressions is an overly complex way to match literal strings.