0

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)
#/
Community
  • 1
  • 1
Pradhan
  • 421
  • 5
  • 17
  • `([^mins]*)` doesn't do what you expect. That means "capture zero or more of anything that isn't "m", "i", "n" or "s". – the Tin Man Jul 12 '12 at 22:43

4 Answers4

1

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]*)/
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • `$1` is super old-school Perl and might confuse maintainers unfamiliar with what it is. `subst` contains all the information you need. `$1` is also global and can get stomped if you're not careful to use it right away. – tadman Jul 12 '12 at 19:59
  • $1 is not super old-school Perl. It is standard regular expression. – SwiftMango Jul 12 '12 at 20:12
1

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]
tadman
  • 208,517
  • 23
  • 234
  • 262
1

[^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.

Don Cruickshank
  • 5,641
  • 6
  • 48
  • 48
0

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"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303