Negative Look-ahead


Negative Look-Ahead patterns are look-around patterns that match only if the text immediately to the right of the match does not match the test-pattern. As with all look-around patterns, the "test pattern" is not part of the match.

This can be better explained with an example, again using our buffer containing a variety of dates:

Initial Conditions
2022-01-14
2022-07-09
2022-10-23
2022-12-20
2023-01-26
2023-03-17
2023-08-06
2023-11-05
COMMANDTop1:1
/\(2022\)\(-1\)\@!

suppose we want to match the year 2022 for each date that is not in Q4 (months 10, 11, and 12). The first step is to create the pattern that matches our desired content, which is simply:

\(2022\)

Now that we have defined the main pattern, the next step is to define the test pattern. We only want to match the year when the month starts with a "1", so we can use the test pattern:

\(-1\)

Finally, to mark the test as a negative look-ahead assertion we use \@! to get the final pattern:

\(2022\)\(-1\)\@!

when we execute this pattern:

Move cursor down
2022-01-14
2022-07-09
2022-10-23
2022-12-20
2023-01-26
2023-03-17
2023-08-06
2023-11-05
NORMAL22%2:1
 

Note that although our main pattern will match any time that the year is 2022, the test matches any month that starts with "1", which cancels the match. As a result, only those line for which the year is 2022 and the month does not start with a "1" are highlighted.