Pradhan
Pradhan

Reputation: 421

Extract text from a string in ruby

I saw a few solutions and came up with the following code. My desired result is 100.02. The required result is always between 'my launch duration=' and 'mins'

mystring ='2012-07-11 22:30:33,536  INFO: 00/00/164/ABCTimeTest: my launch duration= 100.02 mins|z-vndn'
mypattern = /^.*=([^mins]*)/
subst = mystring.match(mypattern)
puts subst

output with the above code: 2012-07-11 22:30:33,536 INFO: 00/00/164/ABCTimeTest: my launch duration= 100.02

Whats wrong in my pattern? correct me with my understanding of this pattern.

#/
#^.*=             ## move from start till = (now I have reached till '=')
#([^mins])        ## capture somethings that starts with mins (thats my 100.2)
#/

Upvotes: 0

Views: 608

Answers (4)

the Tin Man
the Tin Man

Reputation: 160621

I'd use something simple like:

mystring ='2012-07-11 22:30:33,536  INFO: 00/00/164/ABCTimeTest: my launch duration= 100.02 mins|z-vndn'
mystring[/(\S+) mins/, 1] # => "100.02"

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270767

It works fine for me. Don't puts subst, as subst contains the MatchData object. The capture is inside $1 or subst[1].

mystring ='2012-07-11 22:30:33,536  INFO: 00/00/164/ABCTimeTest: my launch duration= 100.02 mins|z-vndn'
mypattern = /^.*=([^mins]*)/
subst = mystring.match(mypattern)

# Contains extra whitespace, so call .strip
puts $1.strip
# 100.02

# Or ...
puts subst[1].strip
# 100.02

To get the 100.02 without the extra whitespace, you can use the following:

mypattern = /^.*=\s*([^\smins]*)/

Upvotes: 1

Don Cruickshank
Don Cruickshank

Reputation: 5948

[^mins] does not match any sequence of characters that's not the exact string mins. It actually means one single character that isn't an 'm', 'i', 'n' or an 's'.

To match the desired text, try something like:

/my launch duration= ([0-9.]*) mins/

This means match a sequence of 0-9 and a period any number of times, but it must be between my launch duration= and mins.

Upvotes: 1

tadman
tadman

Reputation: 211740

Your pattern is correct but you're not using the results correctly. subst is a match object, not the contents of the capture. What you want instead is:

# Show first captured result
puts subst[1]

Upvotes: 1

Related Questions