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.
- 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
The given example will match every N that is followed by and O . Here the (?=O) is the positive lookahead group.
- Negative Lookahead – This will match groups which are not followed by the group specified via the lookaheads
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.
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.
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.
The negative look group indicates that every O should me matched if its not followed by and N .
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.
Also read, Useful Regular Expressions in real life