Introduction
Lookahead and lookbehind, collectively called “lookaround”, are zero-length assertions just like the start and end of line. Lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. They do not consume characters in the string, but only assert whether a match is possible or not. They allow you to perform complex matches based on information that follows or precedes a pattern, without the information within the lookahead assertion forming part of the returned text.Types of lookaround assertion
- Lookahead(?=f) : Asserts that what immediately follows the current position in the string is f
- Lookbehind (?<=f) : Asserts that what immediately precedes the current position in the string is f
- Negative Lookahead (?!f) : Asserts that what immediately follows the current position in the string is not f
- Negative Lookbehind (?<!f) : Asserts that what immediately precedes the current position in the string is not f
Positive lookahead
It asserts that the first part of the pattern must be followed directly by the lookahead element. However, the returned match only contains the text that matches the first part. To define a positive lookahead assertion, create a group, surrounded by parentheses, that starts with a question mark and an equals sign (?=). The text within the parentheses, after the initial equals sign, is the pattern of the lookahead.
Negative Lookahead
It assert that the pattern in the lookahead must not follow the text matched by the initial part of the pattern. To create a negative lookahead, replace the equals sign of the positive variation with an exclamation mark (!).
Positive Lookbehind
Positive lookbehind reverses the order of positive lookahead. The lookbehind part of the pattern, which usually appears at the start of a regular expression, specifies the text that must appear before the text that will be returned. The lookbehind assertion is defined as a group within parentheses. After the opening parenthesis, the string, “?<=” prefixes the pattern to match.
Negative Lookbehind
As with lookahead, you can create negative lookbehind assertions. These specify that a match is only valid if it is preceded by the text in the lookbehind group. Again, the equals sign of the positive variant is replaced with an exclamation mark.
Example
// Positive lookahead RegEx : "grey(?=hound)" String : "i left my grey socks at the greyhound") The regexp "grey(?=hound)" matches grey, but only if it is followed by hound. Thus, the first grey in the text string is not matched. // Negative lookahead The regexp "grey(?!hound)" matches grey, but only if it is not followed by hound. Thus the grey just before socks is matched. // Positive lookbehind The regexp "(?<=grey)hound" matches hound, but only if it is preceded by grey. // Negative lookbehind The regexp "(?<!grey)hound" matches hound, but only if it is not preceded by grey.