3.6. Positive and Negative Lookahead

Naturally, a regular expression is matched against a string in a linear fashion (with backtracking as necessary). Therefore there is the concept of the “current location” in the string—rather like a file pointer or a cursor.

The term lookahead refers to a construct that matches a part of the string ahead of the current location. It is a zero-width assertion because even when a match succeeds, no part of the string is consumed (that is, the current location does not change).

In this next example, the string "New World" will be matched if it is followed by "Symphony" or "Dictionary"; however, the third word is not part of the match:

s1 = "New World Dictionary" s2 = "New World Symphony" s3 = "New World Order" ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.