从ruby中的字符串中提取文本

时间:2012-07-12 19:53:36

标签: ruby

我看到了一些solutions并提出了以下代码。我想要的结果是 100.02 。所需结果始终位于'我的启动持续时间=''分钟'

之间
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

输出以上代码: 2012-07-11 22:30:33,536 INFO:00/00/164 / ABCTimeTest:我的发布时间= 100.02

我的模式出了什么问题?用我对这种模式的理解来纠正我。

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

4 个答案:

答案 0 :(得分:1)

对我来说很好。不要puts subst,因为subst包含MatchData对象。捕获位于$1subst[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

要获得没有额外空格的100.02,您可以使用以下内容:

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

答案 1 :(得分:1)

您的模式是正确的,但您没有正确使用结果。 subst是匹配对象,而不是捕获的内容。你想要的是:

# Show first captured result
puts subst[1]

答案 2 :(得分:1)

[^mins]与任何不是确切字符串mins的任何字符序列都不匹配。它实际上意味着一个不是'm','i','n'或's'的单个字符。

要匹配所需的文字,请尝试以下操作:

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

这意味着匹配0-9的序列和任意次数的句点,但它必须在my launch duration=mins之间。

答案 3 :(得分:0)

我会使用简单的东西:

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"
相关问题