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 ?
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.
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.
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.
You can use this regex to match floating point numbers in the two formats you posted: -
(\d+[,.]\d+)
See Demo on Rubular
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With