MATLAB: Does REGEXPREP return an answer different from what I expect when I use space in the replacing pattern

expressionexpressionsMATLABrefexprepregular

If I enter the following at MATLAB Command Prompt:
res=regexprep('ZZZABAB','^[^A]*A','Q')
the result is QBAB.
If I then enter
res=regexprep('ZZZABAB','^[^A]*A','')
the result is B. I expect the result to be BAB.

Best Answer

The answer received is expected. By default REGEXPREP will repeat the replace as many times as it can.
When executing the following code:
res=regexprep('ZZZABAB','^[^A]*A','')
initially, the beginning of the string (ZZZ) and an 'A' are replaced with ' '. However the operation has not completed, since it has to work on the entire string. Now, because we replaced the initial part of the string by ' ', B appears to be the start of a new string and the operation continues. Hence the result is the last B. In order to force REGEXPREP to perform the replacement just once, use the following syntax:
res=regexprep('ZZZABAB','^[^A]*A','',1)