From: "David A. Black" Date: 2009-07-23T10:43:07+09:00 Subject: Re: Question about text parsing Hi -- On Thu, 23 Jul 2009, spox wrote: > On Wednesday 22 July 2009 14:58:47 Stephen Beard wrote: >> Hello, >> >> I am new to ruby and had a question about parsing text. >> >> I am trying to parse out the first IP address from a string. I have a >> working solution, but it seems like a rather round about way to do it. >> This is my current method: >> >> str = " inet addr:192.168.1.118 Bcast:192.168.1.255 >> Mask:255.255.255.0" >> ipAddr = ((str.split(':'))[1].split)[0] >> >> Is there a better way to do this? Thanks in advance. > > regexp: > str.scan(/addr:([^\s]+)/)[0][0] > > string math: > str.slice(str.index(':')+1, str.index(' B')-str.index(':')-2) Here's a technique involving subscripting a string with a regular expressions. The number 1 at the end causes the whole thing to return the contents of the first parenthetical capture (which is all consecutive non-space characters following the first colon). str[/:(\S+)/,1] David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) Training! Intro to Ruby, with Black & Kastner, September 14-17 (More info: http://rubyurl.com/vmzN)