Created
July 25, 2012 14:24
-
-
Save brentertz/3176445 to your computer and use it in GitHub Desktop.
Ruby regex capture named matches as local variables.
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
# You can name your captured matches and ruby will create local variables for you automatically. | |
# The regex is on Rubular at http://rubular.com/r/HJbhamKAib | |
$ irb | |
1.9.3p0 :001 > s = "Foo Bar Bas <foo@bar.com>" | |
"Foo Bar Bas <foo@bar.com>" | |
1.9.3p0 :002 > /(?<label>.*) <(?<email>[^>]*)/ =~ s | |
0 | |
1.9.3p0 :003 > label | |
"Foo Bar Bas" | |
1.9.3p0 :004 > email | |
"foo@bar.com" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this does not work if you switch the order of the regexp and the string. You will still get a match, but the local variables will not be created. Good tip anyway.