Created
June 23, 2011 14:51
-
-
Save sobstel/1042677 to your computer and use it in GitHub Desktop.
Regex look ahead and look behind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# (?=) 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