The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
How to parse decimal numbers within a string

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Antonio Cangiano

Posts: 333
Nickname: acangiano
Registered: Dec, 2005

Antonio Cangiano is a Ruby hacker
How to parse decimal numbers within a string Posted: Feb 5, 2006 8:58 AM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Antonio Cangiano.
Original Post: How to parse decimal numbers within a string
Feed Title: Zen and the Art of Ruby Programming
Feed URL: http://programmingzen.com/category/ruby/feed/
Feed Description: Antonio Cangiano's blog about Ruby development.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Antonio Cangiano
Latest Posts From Zen and the Art of Ruby Programming

Advertisement

INPUT: a string containing decimal numbers.

OUTPUT: an array containing all the decimal numbers within the given string.

You can accomplish this task very quickly with the String#scan method and the right Regular Expression (regex).

Given a string s, you can use:

numbers = s.scan /[-+]?\d*\.?\d+/  

numbers will be an array whose elements are the decimal numbers within the string s. Note how the regex considers the possible + or – signs in front of the numbers.

If you also wish to match floating point numbers with exponents (scientific notation, e.g. 2.54.e-07), then use the following:

numbers = s.scan /[-+]?\d*\.?\d+([eE][-+]?\d+)?/ 

Read: How to parse decimal numbers within a string

Topic: Sigue la controversia de Java y el Decreto 3.390 Previous Topic   Next Topic Topic: In Pune tomorrow

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use