MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
ans =

1 2
4 8
10 9
19 25
27 34
36 39

Tokens in Replacement Text


When using tokens in replacement text, reference them using $1, $2, etc. instead of \1,
\2, etc. This example captures two tokens and reverses their order. The first, $1, is
'Norma Jean' and the second, $2, is 'Baker'. Note that regexprep returns the
modified text, not a vector of starting indices.

regexprep('Norma Jean Baker', '(\w+\s\w+)\s(\w+)', '$2, $1')

ans =

'Baker, Norma Jean'

Named Capture


If you use a lot of tokens in your expressions, it may be helpful to assign them names
rather than having to keep track of which token number is assigned to which token.

When referencing a named token within the expression, use the syntax \k<name> instead
of the numeric \1, \2, etc.:

poe = ['While I nodded, nearly napping, ' ...
'suddenly there came a tapping,'];

regexp(poe, '(?<anychar>.)\k<anychar>', 'match')

ans =

1×4 cell array

{'dd'} {'pp'} {'dd'} {'pp'}

Named tokens can also be useful in labeling the output from the MATLAB regular
expression functions. This is especially true when you are processing many pieces of text.

2 Program Components

Free download pdf