Skip to content

Instantly share code, notes, and snippets.

@samstokes
Created November 18, 2009 03:28
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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 "foo@example.com" =~ /@(.*)/
$1
else
raise "bad email"
end
# => "example.com"
match = /@(.*)/.match("foo@example.com")
if match
match[1]
else
raise "bad email"
end
# => "example.com"
$1 if "foo@example.com" =~ /@(.*)/ or raise "bad email" # => "example.com"
require 'andand'
/@(.*)/.match("foo@example.com").andand[1] # => "example.com"
"foo@example.com"[/@(.*)/, 1] or raise "bad email"
# => "example.com"
@joshuapinter
Copy link

joshuapinter commented Dec 8, 2018

I found that match = /@(.*)/.match("foo@example.com") gave different results than "foo@example.com" =~ /@(.*)/.

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