The Slice Matcher #
String#[]
and slice
both hand you back matches, right?
>> "redhanded.hobix.com:80"[/:\d+$/] => ":80" >> "Matching Mole -- Little Red Record".slice(/Mo\w+/) => "Mole"
But it’s no good for getting back match groups.
>> "02. One of Us is Dead.mp3"[/^\d+\. (.*)\.mp3$/] => "02. One of Us is Dead.mp3"
Oh, no, wait, it is so good at it!
>> "02. One of Us is Dead.mp3"[/^\d+\. (.*)\.mp3$/, 1] => "One of Us is Dead"
Credit due: Found this while admiring flgr’s one-line fantastic web server he left in the comments several months ago:
require'socket';s=TCPServer.new 80;loop{c=s.accept;c<<"\n"+IO.read( c.gets[/\/(.*) /,1].gsub(/\.{2,}/){})rescue 404;c.close}
Daniel Berger
Kevin Ballard
Daniel, why would non-greedy be useful at all here? It’s not possible for non-greedy to find a different match than greedy does with this regex, but in the common use it is slightly more inefficient (given what I think are likely assumptions about the way the regex engine does matching).
Daniel Berger
Kevin, in this case it’s not an issue, really. It’s just a sloppy habit I don’t want other people to pick up on. That, or my knowledge from Friedl’s book is woefully out of date.
flgr
And I thought I knew about this from your very nice list of 1.8 changes.
Anyway, there’s a lot of goodness hidden in Ruby’s standard library. :)
MenTaLguY
Whoa, cool. Okay. I will be using this.
harold
jim
Mmmm, Matching Mole!
Pistos
I knew about string[ regexp, group_index ] from I-don’t-remember-where, but I recently learned about this from the core documentation :
Pistos.emotions << Joy.new
automatthew
I saw a boy’s T-shirt today.
phil76
the above works with every array:
a, b, c = [1, 2, 3] => a = 1, b = 2, c = 3
or flip some values?
a = 1 b = 2 a, b = b, a => a = 2, b = 1
big smile
phil76
argh …
the above works with every array:
or flip some values?
big smile
Comments are closed for this entry.