Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract float numbers from a string in ruby? [closed]

Tags:

regex

ruby

I have string with an amount different currencies in it, e.g,

"454,54$", "Rs566.33", "discount 88,0$" etc.

The pattern is not consistent and I want to extract only float numbers from the string and the currency.

How I can achieve this in Ruby ?

like image 209
amjad Avatar asked Dec 04 '12 15:12

amjad


People also ask

How do I extract numbers from a string in Ruby?

extract numbers from a string : scan « String « Ruby uses \d to match any digit, and the + that follows \d makes \d match as many digits in a row as possible. scan through all the vowels in a string: [aeiou] means "match any of a, e, i, o, or u." Just like /\w+/, but doesn't consider underscore part of a word.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.

How do you convert string to int in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.


1 Answers

You can use this regex to match floating point numbers in the two formats you posted: -

(\d+[,.]\d+)

See Demo on Rubular

like image 157
Rohit Jain Avatar answered Sep 28 '22 06:09

Rohit Jain