Skip to content

Instantly share code, notes, and snippets.

@samstokes
Created November 18, 2009 03:28
Show Gist options
  • Save samstokes/237534 to your computer and use it in GitHub Desktop.
Save samstokes/237534 to your computer and use it in GitHub Desktop.
How to extract groups from a regex match in Ruby without globals or temporary variables. Code snippets supporting http://blog.samstokes.co.uk/post/251167556/regex-style-in-ruby
if "[email protected]" =~ /@(.*)/
$1
else
raise "bad email"
end
# => "example.com"
match = /@(.*)/.match("[email protected]")
if match
match[1]
else
raise "bad email"
end
# => "example.com"
$1 if "[email protected]" =~ /@(.*)/ or raise "bad email" # => "example.com"
require 'andand'
/@(.*)/.match("[email protected]").andand[1] # => "example.com"
"[email protected]"[/@(.*)/, 1] or raise "bad email"
# => "example.com"
@joshuapinter
Copy link

joshuapinter commented Dec 8, 2018

I found that match = /@(.*)/.match("[email protected]") gave different results than "[email protected]" =~ /@(.*)/.

Same Regex and same body but result was different so ended up using =~.

I take it back. I might not have been using .captures after using .match(). It works great, actually.

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