Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a regex to extract numeric values from a string?

Tags:

regex

ruby

I have a string str = "$ 9.0 / hr" or str = "$9.0/hr". I only want the integer value from this in this case 9.0

Language is Ruby 1.9.2

like image 666
Bhushan Lodha Avatar asked Dec 02 '22 23:12

Bhushan Lodha


1 Answers

I'd use:

number = str[ /\d*(?:\.\d+)?/ ]

Or, if a leading 0 is required for values less than 1.0,

number = str[ /\d+(?:\.\d+)?/ ]

If you might have other numbers in the string, and only want the (first) one that has a dollar sign before it:

number = str[ /\$\s*(\d+(?:\.\d+)?)/, 1 ]

If it's guaranteed that there will (must) be a decimal place and digit(s) thereafter:

number = str[ /\$\s*(\d+\.\d+)/, 1 ]

Hopefully you can mix and match some of these solutions to get what you need.

like image 136
Phrogz Avatar answered Mar 23 '23 07:03

Phrogz