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