MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

varies in each character vector. If the count did not vary, you could use the expression
X{n} to indicate that you want to match n of these characters. But, a constant value of n
does not work in this case.


The solution used here is to capture the leading count number (e.g., the 5 in the first
character vector of the cell array) in a token, and then to use that count in a dynamic
expression. The dynamic expression in this example is (??X{$1}), where $1 is the value
captured by the token \d+. The operator {$1} makes a quantifier of that token value.
Because the expression is dynamic, the same pattern works on all three of the input
vectors in the cell array. With the first input character vector, regexp looks for five X
characters; with the second, it looks for eight, and with the third, it looks for just one:


regexp(chr, '^(\d+)(??X{$1})$', 'match', 'once')


ans =


1×3 cell array


{'5XXXXX'} {'8XXXXXXXX'} {'1X'}


Commands That Modify the Match Expression — (??@cmd)


MATLAB uses the (??@cmd) operator to include the results of a MATLAB command in the
match expression. This command must return a term that can be used within the match
expression.


For example, use the dynamic expression (??@flilplr($1)) to locate a palindrome,
“Never Odd or Even”, that has been embedded into a larger character vector.


First, create the input string. Make sure that all letters are lowercase, and remove all
nonword characters.


chr = lower(...
'Find the palindrome Never Odd or Even in this string');


chr = regexprep(chr, '\W*', '')


chr =


'findthepalindromeneveroddoreveninthisstring'


Locate the palindrome within the character vector using the dynamic expression:


Dynamic Regular Expressions
Free download pdf