Skip to content

Instantly share code, notes, and snippets.

@brentertz
Created July 25, 2012 14:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentertz/3176445 to your computer and use it in GitHub Desktop.
Save brentertz/3176445 to your computer and use it in GitHub Desktop.
Ruby regex capture named matches as local variables.
# 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"
@Patru
Copy link

Patru commented Aug 9, 2013

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment