代码之家  ›  专栏  ›  技术社区  ›  Christopher Francisco

正则表达式模式未捕获匹配的第二个匹配项

  •  0
  • Christopher Francisco  · 技术社区  · 6 年前

    我有绳子:

    Error: heroku 6.14.38 is already installed
    To upgrade to 7.7.1, run `brew upgrade heroku`
    

    我正在做 .slice(/([\d+\.]+)/) 它给了我 6.14.38 ,但不是 7.7.1 .

    我怎样才能得到它呢?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Paolo    6 年前

    你可以使用 scan 方法:

    str = "Error: heroku 6.14.38 is already installed
    To upgrade to 7.7.1, run `brew upgrade heroku`"
    puts(str.scan(/((?:\d+\.)+\d+)/))
    

    印刷品:

    6.14.38
    7.7.1
    
        2
  •  0
  •   Cary Swoveland    6 年前
    str = "Error: heroku 6.14.38 is already installed
    To upgrade to 7.7.1, run `brew upgrade heroku`"
    
    r = /
        \d{1,2}  # match one or two digits
        \.       # match decimal
        \d{1,2}  # match two digits
        \.       # match decimal
        \d{1,2}  # match two digits
        .+?      # match any number of characters, lazily
        \K       # discard match so far
        \d{1,2}  # match one or two digits
        \.       # match decimal
        \d{1,2}  # match two digits
        \.       # match decimal
        \d{1,2}  # match two digits
        /xm      # free-spacing regex definition and multiline modes
    
    str[r]
      #=> "7.7.1"