How to write a regular expression to extract numeric values ​​from a string?

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

Language - Ruby 1.9.2

+4
source share
4 answers

I would use:

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

Or, if values ​​less than 1.0 require a start of 0,

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

If you can have other numbers on the line and just want (the first) that has a dollar sign in front of it:

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

If this guarantees that after this there will be (should) be a decimal place and digits (digits):

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

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

+7
source

No regex:

 str.delete("^0-9.") 
+5
source

If your prices always have the dollars.cents format (which may be related to prices), use this regex:

 "$ 9.0 / hr".match(/\d+\.\d+/)[0] # => 9.0 "$9.0/hr".match(/\d+\.\d+/)[0] # => 9.0 

Otherwise, you should take the regular expression from Phrogz's answer.

+4
source

I don't know ruby, but should the regex be \d+(?:\.\d+)? . This will also work with "$9/hr"

+1
source

Source: https://habr.com/ru/post/1392735/


All Articles