hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

The Slice Matcher #

by why in inspect

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}
said on 06 Jan 2006 at 20:37
Try non-greedy:
"02. One of Us is Dead.mp3"[/^\d+\.(.*?)\.mp3$/, 1]
said on 06 Jan 2006 at 21:46

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).

said on 06 Jan 2006 at 23:39

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.

said on 07 Jan 2006 at 09:14

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. :)

said on 07 Jan 2006 at 11:35

Whoa, cool. Okay. I will be using this.

said on 07 Jan 2006 at 12:18
How about?
the_title = "02. One of Us is Dead.mp3" 
the_title[/^\d+\..*(....)\.mp3$/, 1] = 'Live'
puts the_title
said on 07 Jan 2006 at 13:04

Mmmm, Matching Mole!

said on 24 Jan 2006 at 11:19

I knew about string[ regexp, group_index ] from I-don’t-remember-where, but I recently learned about this from the core documentation :

all,f1,f2,f3 = *( /(.)(.)(\d+)(\d)/.match( "THX1138." ) )
all   #=> "HX1138" 
f1    #=> "H" 
f2    #=> "X" 
f3    #=> "113" 

Pistos.emotions << Joy.new

said on 07 Feb 2006 at 10:12

I saw a boy’s T-shirt today.

said on 08 Feb 2006 at 21:59

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

said on 08 Feb 2006 at 22:00

argh …

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

Comments are closed for this entry.