PeaceDefener
PeaceDefener

Reputation: 638

How do I extract integers from strings using a regular expression?

I am fetching arbitrary strings from different sources that might contain integers. Here are some examples:

  1. "He owns 3 cars"
  2. "John has $23 and 50 cents"
  3. "The range is 1-12 cm"

I would like to parse them so that the output will be like:

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

Upvotes: 2

Views: 140

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

"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"

Upvotes: 6

Related Questions