MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1
To be more efficient, however, you can build a single phrase that applies to all of these
search terms:

Translate this phrase into a regular expression (to be explained later in this section) and
you have:

pattern = 'k(ilo)?m(eters)?(/|\sper\s)h(r|our)?';

Now locate one or more of the terms using just a single command:

text = ['The high-speed train traveled at 250 ', ...
'kilometers per hour alongside the automobile ', ...
'travelling at 120 km/h.'];
regexp(text, pattern, 'match')

ans =

1×2 cell array

{'kilometers per hour'} {'km/h'}

There are four MATLAB functions that support searching and replacing characters using
regular expressions. The first three are similar in the input values they accept and the
output values they return. For details, click the links to the function reference pages.

Function Description
regexp Match regular expression.
regexpi Match regular expression, ignoring case.
regexprep Replace part of text using regular expression.
regexptranslate Translate text into regular expression.

2 Program Components

Free download pdf