From: Wesley Chen Date: 2009-07-23T10:50:41+09:00 Subject: Re: Question about text parsing --000e0cd3101cf9112d046f55b694 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Perfect. Thanks. Wesley Chen. On Thu, Jul 23, 2009 at 9:43 AM, David A. Black wrote: > 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) > > --000e0cd3101cf9112d046f55b694--