Extract Number from String in Ruby

Extract number from string in Ruby

a.map {|x| x[/\d+/]}

How to extract numbers from string containing numbers+characters into an array in Ruby?

Try using String#scan, like this:

str.scan(/\d+/)
#=> ["123", "84", "3", "98"]

If you want integers instead of strings, just add map to it:

str.scan(/\d+/).map(&:to_i)
#=> [123, 84, 3, 98]

How to extract number out of url string ruby

Something like: /\d+$/ should get all digits at the end of the string

extract number with seperated point in a string ruby

You can use method split by space in ruby

a = 'ProductX credit 1.000'
a.split(" ").last

Result

"1.000"

How to extract digits from a String and transform them into an Integer

The #gsub method can replace all non-digit characters in the String and then you can transform it into an Integer with #to_i:

"1 026 personnes aiment ça".gsub(/\D/, "").to_i
#~> 1026

Retrieve number from the string pattern using regular expression

I'm not sure on the syntax in Ruby, but the regular expression would be "(\d+)" meaning a string of digits of size 1 or more. You can try it out here: http://www.rubular.com/

Updated:
I believe the syntax is /(\d+)/.match(your_string)



Related Topics



Leave a reply



Submit