Lookahead and Lookbehind in regex tutorial

REGEX

Lookaheads are one of the most powerful feature in regular expressions.  Lookaheads helps you to broaden your matches. You really may need to depend on these lookaheads in many scenarios. For instance, if you want to match every  “N” in the paragraph which is not followed by  a “O” . You cannot use the not (^) , say  /N[^O]/ as it will match the second character also.  So here comes the use of lookaheads and lookbehinds.

1.Lookaheads

    • Postive Lookahead– This will match groups which are followed by the group specified via the lookaheads. Have a look at this example, we need to match every N that is followed by an O .

This would the positive lookahead regex

Regex :

 N(?=O)

The given example will match every  N that is followed by and O . Here the (?=O) is the positive lookahead group.

Live Demo to Positive Look aheads

  • Negative Lookahead – This will match groups which are not followed by the group specified via the lookaheads

Regex :

N(?!O)

This matches exactly the opposite what the positve lookahead matched. This matches every N that is not followed by an O , the negative look ahead group is (?!O), and the !O represent that its a negative look ahead.

Live Demo to Negative Look aheads

2. Lookbehinds

The concept of lookbehinds are simple, its just the opposite of the look aheads. It matches the very next group obeying the condition of the Look behind group

  • Postive Lookbehind – This will match the groups which which are followed by the group specified via the lookbehind.

example : Consider the case were we need to match every O that comes right after an N.

Regex : 

(?<=N)O

The (?<=N) is the positive look behind group and it indicates that every O should me matched if its followed by and N .Live demo link to postive look behind 

  • Negative Lookbehind - This will match the groups which which are not followed by the group specified via the lookbehind.

Regex : 

(?

The negative look group indicates that every O should me matched if its not followed by and N .

Live demo link to negative look behind

This theory is very much helpful in matching the contents inside brackets () or html tags (<>) .

Practical Examples Of Regular Expressions- Match contents inside  a bracket.

 (?<=\()(.*)(?=\))

Here the Positive look behind group  (?<=\() and positive look ahead  group (?=\)) makes the total expression to match the whole content inside the bracket. "\"  is use escape the Brackets.

Live Demo to regex to match contents inside brackets

Also read, Useful Regular Expressions in real life

About the author

Linjo Joson

Linjo is a PHP developer who loves to write about online businesses and marketing ideas

Add comment

Categories