Re:What are your Ruby Regex Idioms?
by sofal on Monday November 30, 2009 @09:51AM
(#967881)
One of my favorite patterns:
[ Parent
| on HN ]
If you're capturing something you don't want, you can always prefix your match with '?:' to have a non-capturing group.
FWIW, I personally prefer the #match method. Some of the examples in this article just make me want to hurt people. Especially usage of $1, $2, etc.
In that case, /([^@]+)@(.+$)/.match("[email protected]")[0] returns the whole string matched by the expression, and [1] and [2] return the first and second groups. That's why the throwaway is there. To get rid of the throwaway, this is a possibility:
username, domain = */([^@]+)@(.+$)/.match("[email protected]").captures
Of course, your string better match, otherwise you'll get a NoMethodError.
Re:What are your Ruby Regex Idioms?
by steveklabnik on Monday November 30, 2009 @11:20AM
(#968060)
$1 and $2 are probably still there do to Ruby's Perl heritage. I don't particularly mind their use, but that's probably due to my long history with Perl.
Nice. I am intrigued by the leading underscore, are you just using that as a throwaway variable? You could get the username and domain on their own with:
username, domain = [*/([^@]+)@(.+$)/.match("[email protected]")][1..-1]
And it is super readable.this works as well...
username,domain = */([^@]+)@(.+$)/.match("[email protected]").captures