如何使用正则表达式从字符串中提取整数?

时间:2013-06-16 18:15:47

标签: ruby regex

我从可能包含整数的不同来源获取任意字符串。以下是一些例子:

  1. "He owns 3 cars"
  2. "John has $23 and 50 cents"
  3. "The range is 1-12 cm"
  4. 我想解析它们,以便输出如下:

    1. "3"
    2. "23-50"
    3. "1-12"

1 个答案:

答案 0 :(得分:5)

"John has 23$ and 50 cents".scan(/\d+/).join("-") # => "23-50"
"The range is 1-12 cm".scan(/\d+/).join("-") # => "1-12"
"He owns 3 cars".scan(/\d+/).join("-") # => "3"
相关问题