23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Regular Expressions<br />

starting match: [^abcdefghij]<br />

starting match: [a^bcdefghij]<br />

starting match: [ab^cdefghij]<br />

starting match: [abc^defghij]<br />

starting match: [abcd^efghij]<br />

starting match: [abcde^fghij]<br />

starting match: [abcdef^ghij]<br />

Dynamic Operators for the Replacement Expression<br />

The three types of dynamic expressions discussed above can be used only<br />

in the match expression (second input) argument of the regular expression<br />

functions. <strong>MATLAB</strong> provides one more type of dynamic expression; this one<br />

is for use in a replacement string (third input) argument of the regexprep<br />

function.<br />

Dynamic Commands that Modify the Replacement Expression —<br />

${cmd}. The ${cmd} operator modifies the contents of a regular expression<br />

replacement string, making this string adaptable to parameters in the<br />

input string that might vary from one use to the next. As with the other<br />

dynamic expressions used in <strong>MATLAB</strong>, you can include any number of these<br />

expressions within the overall replacement expression.<br />

In the regexprep call shown here, the replacement string is<br />

'${convert($1,$2)}'. In this case, the entire replacement string is a<br />

dynamic expression:<br />

regexprep('This highway is 125 miles long', ...<br />

'(\d+\.?\d*)\W(\w+)', '${convert($1,$2)}')<br />

The dynamic expression tells <strong>MATLAB</strong> to execute an M-file function named<br />

convert using the two tokens (\d+\.?\d*) and (\w+), derived from the<br />

string being matched, as input arguments in the call to convert. The<br />

replacement string requires a dynamic expression because the values of $1<br />

and $2 are generated at runtime.<br />

The following example defines the M-file named convert that converts<br />

measurements from imperial units to metric. To convert values from the<br />

string being parsed, regexprep calls the convert function, passing in values<br />

for the quantity to be converted and name of the imperial unit:<br />

3-65

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!