Skip to content

Instantly share code, notes, and snippets.

@sobstel
Created June 23, 2011 14:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobstel/1042677 to your computer and use it in GitHub Desktop.
Save sobstel/1042677 to your computer and use it in GitHub Desktop.
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