Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookahead vs lookbehind

I have a hard time to understand the concepts of "lookahead" and "lookbehind". For example, there is a string "aaaaaxbbbbb". If we look at "x", does lookahead mean looking "x" towards "bbbbb" or "aaaaa"? I mean the direction.

like image 338
Bigeyes Avatar asked Jul 23 '12 20:07

Bigeyes


1 Answers

If the regex is x(?=insert_regex_here) that is a (positive) look*ahead*, which looks ahead, or forwards, in other words towards "bbbb". It means "find an x that is followed by insert_regex_here".

If the regex is (?<=insert_regex_here)x that is a (positive) look*behind*, which looks behind, or backwards, in other words towards "aaaa". It means "find an x that is preceded by insert_regex_here".

You can also have negative lookahead x(?!insert_regex_here) meaning "x not followed by insert_regex_here", and negative lookbehind (?<!insert_regex_here)x, meaning "x not preceded by insert_regex_here".

(The above (?= and (?<! etc are Perl regex syntax - the syntax might be slightly different depending on your flavour of regex).

I recommend you read the link that Chad gave in the comments. It has examples.

like image 60
mathematical.coffee Avatar answered Sep 20 '22 15:09

mathematical.coffee