s
ans =
1×1 cell array
{'mississippi'}
To demonstrate how versatile this type of dynamic expression can be, consider the next
example that progressively assembles a cell array as MATLAB iteratively parses the input
text. The (?!) operator found at the end of the expression is actually an empty lookahead
operator, and forces a failure at each iteration. This forced failure is necessary if you want
to trace the steps that MATLAB is taking to resolve the expression.
MATLAB makes a number of passes through the input text, each time trying another
combination of letters to see if a fit better than last match can be found. On any passes in
which no matches are found, the test results in an empty character vector. The dynamic
script (?@if(~isempty($&))) serves to omit the empty character vectors from the
matches cell array:
matches = {};
expr = ['(Euler\s)?(Cauchy\s)?(Boole)?(?@if(~isempty($&)),' ...
'matches{end+1}=$&;end)(?!)'];
regexp('Euler Cauchy Boole', expr);
matches
matches =
1×6 cell array
{'Euler Cauchy Bo...'} {'Euler Cauchy '} {'Euler '} {'Cauchy Boole'} {'Cauchy '} {'Boole'}
The operators $& (or the equivalent $0), $`, and $' refer to that part of the input text
that is currently a match, all characters that precede the current match, and all
characters to follow the current match, respectively. These operators are sometimes
useful when working with dynamic expressions, particularly those that employ the (?
@cmd) operator.
This example parses the input text looking for the letter g. At each iteration through the
text, regexp compares the current character with g, and not finding it, advances to the
next character. The example tracks the progress of scan through the text by marking the
current location being parsed with a ^ character.
2 Program Components