MATLAB: Regexprep incorrect multiple replacement

regexregexprep

I am trying to replace numbers in a char vector with different numbers using regexprep.
Let's say we have the following char vector as input:
str = 'abc(1,2,3)';
I would like to replace '1','2' and '3' with different numbers.
Let's say I want to replace the numbers with the following numbers:
rep = '{'5';'8';'3'};
My desired output is:
str = 'abc(5,8,3)';
The format for using regexprep is:
regexprep(str,expression,replace)
I have tried to solve the problem in two ways:
  • One expression.
expression = '\d';
replace = {'5';'2';'3'};
regexprep(str,expression,replace)
ans = 'abc(3,3,3)'
The output is incorrect, despite the documentation stating:
If replace is a cell array of N character vectors and expression is a single character vector, then regexprep attempts N matches and replacements.
  • Multiple expressions.
expression = {'\d';'\d';'\d'};
replace = {'5';'2';'3'};
regexprep(str,expression,replace)
ans = 'abc(3,3,3)'
The output for the second case is incorrect, despite the documentation stating:
If both replace and expression are cell arrays of character vectors, then they must contain the same number of elements. regexprep pairs each replace element with its corresponding element in expression.
In both cases regexprep is replacing all three matches using only the last value from the replace cell array, rather than all three.
What am I missing?

Best Answer

regexprep (S, {A, B }, { P, Q })
is the same as
regexprep( regexprep(S, A, P), B, Q)
That is, the first pair is applied to the entire string, and the second pair is applied to the string that results.
It appears to you that only the third was done because your replacement text happens to match the second and third pattern and got rereplaced.
The 'once' option will not solve the problem.