Lookahead and Lookbehind

Some notes on using lookahead and lookbehind when using grep.

Basic usage:

Pattern Explanation Name
(?=...) look ahead for this Lookahead
(?<=...) look behind for this Lookbehind
(?!...) look ahead and reject this Negative Lookahead
(?<!...) look behind and reject this Negative Lookbehind

For documentation on Linux, see man 3 pcrepattern.

Example 1

Here's our toy file, named test.md:

this is a test
it is only a test
the test is this
how about this test

Lookahead

Reminder: (?=...)

To do a grep lookahead, means to match the term only if something comes after it. In this example, matches test followed by a space but does not include the space in the match:

grep -P 'test(?=[[:space:]])' test.md
the test is this

Lookbehind

Reminder: (?<=...)

To do a grep lookbehind, means to match the term only if something comes before it. In this example, matches test if preceded by this and a space:

grep -P '(?<=this[[:space:]])test' test.md
how about this test

Negative Lookahead

Reminder: (?!...)

To do a grep negative lookahead, means to match the term only if something does not come after it. In this example, matches test if not followed by a space and is:

grep -P 'test(?![[:space:]]is)' grep.txt
this is a test
it is only a test
how about this test

Negative Lookbehind

Reminder: (?<!...)

To do a grep negative lookbehind, means to match the term only if something does not come before it. In this example, matches test if not preceded by this and a space:

grep -P '(?<!this[[:space:]])test' grep.txt
this is a test
it is only a test
the test is this

Example 2

Toy example:

<h1>Title</h1>
<h2>Subtitle</h2>
<p>This is a toy HTML file.</p>
<p>Here is an <a href="https://example.com">example link</a>.</p>

Lookahead

Reminder: (?=...)

The following matches file and the period if followed by a </p>:

grep -P 'file[[:punct:]](?=</p>)' test.md
<p>This is a toy HTML file.</p>

Lookbehind

Reminder: (?<=...)

The following matches for the letter T (case sensitive) if preceded by a <p> tag:

grep -P '(?<=<p>)T' grep.txt
<p>This is a toy HTML file.</p>

Negative Lookahead

Reminder: (?!...)

The following matches the <p> tag if not followed by the letter T (case sensitive):

grep -P '<p>(?!T)' grep.txt
<p>Here is an <a href="https://example.com">example link</a></p>

Negative Lookbehind

The following matches the term title (case insensitive) if not preceded by sub (case insensitive):

Reminder: (?<!...)

grep -Pi '(?<!sub)title' grep.txt
<h1>Title</h1>

grep -Pio '(?<!sub)title' grep.txt
Title