MATLAB: Regexp lookbehind and lineanchors

lineanchorslookbehindMATLABregexregexpregular expressions

Could someone help me to understand why
st = ' a b c';
pattern = '(?<=^\s*)c';
regexp(st,pattern,'lineanchors')
ans =
[]
i.e., does not match (as I expected), while
st2 = [newline,st];
regexp(st2,pattern,'lineanchors')
ans =
7
i.e., finds a match?
My intent is to match 'c' that is preceded by the beginning of a line and zero or more white character. How should I do?

Best Answer

"My intent is to match 'c' that is preceded by the beginning of a line and zero or more white character."
In the character array, ' a b c', the character, 'c', is (after the beginning of the line) preceded not only by whitespace but also by the characters 'a' and 'b'. Thus, [] is the expected result. Try
%%
chr = ' a b c';
xpr = '(?<=^[ ab]*)c';
regexp( chr, xpr, 'match', 'lineanchors' )
that returns
ans =
1×1 cell array
{'c'}
I fail to understand the behavior of your second example. I expect [], not 7. It's looks like a bug to me.
/R2018b
ADDENDUM
I learned something about the option,'once', the other day. It affects the type of the output. In this case the output is a character row instead of a cell array containing the character row. Thus,
>> regexp( chr, xpr, 'match', 'lineanchors', 'once' )
ans =
'c'