Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

Chapter 8

In the first line, all parts of the regular expression, including the lookahead, are satisfied, so there is a match.

In the second line, although the character sequence sentence can be matched, the lookahead fails. With no occurrence of the character sequence sequence, there is no match on that line.

On the third line, the character sequence sentence cannot be matched, so there is no match on that line.

On the fourth line, both sentence and sequence occur, but in the wrong order to satisfy the constraint imposed by the lookahead.

Negative Lookahead

Negative lookahead is the process of matching a sequence of characters constrained by an additional requirement that the sequence must not be followed by some other sequence of characters.

For example, in the Star Training Company example, you might want to find occurrences of the sequence of characters s, t, a, and r when they are not followed by a space character and the word Training. That would allow you to find occurrences of the sequence of characters s, t, a, and r that are less likely to refer to Star as part of the name of Star Training Company.

Negative lookahead is written as an opening parenthesis followed by an exclamation point; then the string to be looked for; and, finally, the closing parenthesis. So if you wanted to match a sequence of characters not followed by the word Training, you could use the following as the lookahead part of the regular expression when using tools and languages that support the \b metacharacter:

(?!\bTraining\b)

Negative lookahead can be usefully combined with other constraints. For example, by specifying that the matching process is case-sensitive and using the pattern (lowercase) star, you can keep occurrences of Star from successfully matching the supplied pattern.

The problem definition can be stated as follows:

Match the sequence of character S, t, a, and r, but only when that sequence of characters is not followed by a space character and the sequence of characters T, r, a, i, n, i, n, and g.

Try It Out

Negative Lookahead

1.Open PowerGrep, and enter the pattern Star(?! Training) in the Search text area.

2.In the Folder text box, enter the folder name C:\BRegExp\Ch08.

3.In the File Mask text, box enter the filename StarOriginal.txt, and click the Search button.

4.Inspect the results in the Results area, as shown in Figure 8-4. (Due to the way that PowerGrep interprets line breaks, you will likely find lines that scroll off the screen in a way similar to that shown in the figure.)

Notice that none of the six occurrences of Star before a space character followed by the character sequence Training matches.

202