MATLAB Programming Fundamentals - MathWorks

(やまだぃちぅ) #1

Overlapping Matches


Lookahead assertions do not consume any characters in the text. As a result, you can use
them to find overlapping character sequences.

For example, use lookahead to find every sequence of six nonwhitespace characters in a
character vector by matching initial characters that precede five additional characters:

chr = 'Locate several 6-char. phrases';
startIndex = regexpi(chr,'\S(?=\S{5})')

startIndex =

1 8 9 16 17 24 25

The starting indices correspond to these phrases:

Locate severa everal 6-char -char. phrase hrases

Without the lookahead operator, MATLAB parses a character vector from left to right,
consuming the vector as it goes. If matching characters are found, regexp records the
location and resumes parsing the character vector from the location of the most recent
match. There is no overlapping of characters in this process.

chr = 'Locate several 6-char. phrases';
startIndex = regexpi(chr,'\S{6}')

startIndex =

1 8 16 24

The starting indices correspond to these phrases:

Locate severa 6-char phrase

Logical AND Conditions


Another way to use a lookahead operation is to perform a logical AND between two
conditions. This example initially attempts to locate all lowercase consonants in a
character array consisting of the first 50 characters of the help for the normest function:

helptext = help('normest');
chr = helptext(1:50)

2 Program Components

Free download pdf