Skip to main content

Lookahead and Lookbehind regex assertions explained with an example

Lookahead and Lookbehind assertions, also known as Lookaround assertions are basically special type  of non-matching group. It is a condition that must be satisfied in order to return the match to an expression. These are of zero-length i.e. the match is grouped and there is no change in the position of regex pointer.

Positive Lookahead Assertion :

Syntax :  /(?=regex-expression)/

Example : Let's say if we want to capture the word "background" only if it is in a camel case word "backgroundColor".

/background(?=Color)/      

=>     This will match "background" as a group for text  "backgroundColor" and no match for "backgroundText"


Negative Lookahead Assertion :

Syntax :  /(?!regex-expression)/

Example : Let's say if we want to capture the word "background" only if it is NOT in a camel case word "backgroundColor".

/background(?!Color)/      

=>     This will match "background" as a group for text  "backgroundText" and no match for "backgroundColor"

Positive Lookbehind Assertion :

Syntax :  /(?<=regex-expression)/

Example : Let's say if we want to capture the word "hockey" only if is preceeded with "ice" i.e.  for the word icehockey

/(?<=ice)hockey/      

=>     This will match "hockey" as a group for text "icehockey" and no match for "fieldhockey"

Negative Lookbehind Assertion :

Syntax :  /(?<!regex-expression)/

Example : Let's say if we want to capture the word "hockey" only if is NOT preceeded with "ice" i.e.  for the word icehockey

/(?<!ice)hockey/      

=>     This will match "hockey" as a group for text "fieldhockey" and no match for "icehockey"

Comments