Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Regex look ahead and look behind
# (?=) Positive look ahead assertion foo(?=bar) matches foo when followed by bar.
"Best player ever is Leo Messi.".match(/Leo(?=\s?Messi)\s\w+/)
=> ["Leo Messi"]
# (?!) Negative look ahead assertion foo(?!bar) matches foo when not followed by bar.
> "Or maybe Javier Mascherano? Or Javier Zanetti?.".scan(/Javier(?!\s?Mascherano)\s\w+/)
=> ["Javier Zanetti"]
# (?<=) Positive look behind assertion (?<=foo)bar matches bar when preceded by foo.
"Some say it is Sergio Aguero, but Sergio Batista does not let him play much".scan(/\w+\s(?<=Sergio\s)\w+/)
=> ["Sergio Aguero", "Sergio Batista"]
# (?<!) Negative look behind assertion (?<!foo)bar matches bar when not preceded by foo.
"And we cannot forget about Maxi Rodriguez, and not Clemente Rodriguez.".scan(/\w+\s(?<!Clemente\s)Rodriguez/)
=> ["Maxi Rodriguez"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment