正则表达式模式未捕获匹配的第二次出现

时间:2018-08-02 23:10:09

标签: ruby regex

我有一个字符串:

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 个答案:

答案 0 :(得分:3)

您可以使用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

答案 1 :(得分:0)

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"