【问题标题】:Extract text from a string in ruby从ruby中的字符串中提取文本
【发布时间】:2012-07-12 15:51:36
【问题描述】:

看了几个solutions,想出了下面的代码。我想要的结果是 100.02。所需结果始终介于 'my launch duration=''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

使用上述代码输出: 2012-07-11 22:30:33,536 INFO: 00/00/164/ABCTimeTest: my launch duration= 100.02

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

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

【问题讨论】:

  • ([^mins]*) 不符合您的预期。这意味着“捕获零个或多个不是“m”、“i”、“n”或“s”的东西。

标签: ruby


【解决方案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 是超级老式的 Perl,可能会使不熟悉它的维护者感到困惑。 subst 包含您需要的所有信息。 $1 也是全局的,如果您不小心立即使用它,可能会被踩到。
  • $1 不是超级老式的 Perl。它是标准的正则表达式。
【解决方案2】:

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

# Show first captured result
puts subst[1]

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

      我会使用一些简单的东西,例如:

      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"
      

      【讨论】:

        猜你喜欢
        • 2012-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多