Created
November 18, 2009 03:28
-
-
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
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
if "[email protected]" =~ /@(.*)/ | |
$1 | |
else | |
raise "bad email" | |
end | |
# => "example.com" |
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
match = /@(.*)/.match("[email protected]") | |
if match | |
match[1] | |
else | |
raise "bad email" | |
end | |
# => "example.com" |
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
$1 if "[email protected]" =~ /@(.*)/ or raise "bad email" # => "example.com" | |
require 'andand' | |
/@(.*)/.match("[email protected]").andand[1] # => "example.com" |
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
"[email protected]"[/@(.*)/, 1] or raise "bad email" | |
# => "example.com" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found thatmatch = /@(.*)/.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.