# Regexp for finding floats in a string

**URL:** <https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923>\
**Category:** Ruby\
**Created:** [August 15, 2006, 2:20pm UTC](https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923 "2006-08-15T14:20:26Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bil\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/848f3c/32.png) [@Bil\_K](https://www.ruby-forum.com/u/Bil_K)\
**Post date:** [August 15, 2006, 2:20pm UTC](https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923/1 "2006-08-15T14:20:26Z")

</div>

What RegExp should I be using for floats?

Currently, I have /[-+0-9eE.]+/, viz,

require ‘test/unit’  
class TestFloatRegExp \< Test::Unit::TestCase  
def test\_finds\_em  
%w{ 1 -2 3.0 0.4 5.0e+5 -6e+06 .7E+7 }.each do |string|  
assert( string.match(/[-+0-9eE.]+/), “no match \>\>#{string}\<\<” )  
end  
end  
end

---

<div class="post-metadata">

**Author:** ![Bil\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/848f3c/32.png) [@Bil\_K](https://www.ruby-forum.com/u/Bil_K)\
**Post date:** [August 15, 2006, 2:20pm UTC](https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923/2 "2006-08-15T14:20:26Z")

</div>

On Aug 15, 2006, at 12:50 AM, Bil K. wrote:

> end  
> end

Have a look at the regexp in

perldoc -q float

– fxn

PS: Your mail client runs on a Mac, that works there.

---

<div class="post-metadata">

**Author:** ![Bil\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/848f3c/32.png) [@Bil\_K](https://www.ruby-forum.com/u/Bil_K)\
**Post date:** [August 16, 2006, 3:53pm UTC](https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923/3 "2006-08-16T15:53:25Z")

</div>

Xavier N. wrote:

> Have a look at the regexp in
> 
> perldoc -q float

/^([±]?)(?=\d|.\d)\d\*(.\d\*)?(Ee)?$/

Ouch!

Thanks; I think. 🙂

Regards,

---

<div class="post-metadata">

**Author:** ![Bil\_K](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/848f3c/32.png) [@Bil\_K](https://www.ruby-forum.com/u/Bil_K)\
**Post date:** [August 17, 2006, 8:05pm UTC](https://www.ruby-forum.com/t/regexp-for-finding-floats-in-a-string/64923/4 "2006-08-17T20:05:58Z")

</div>

On 8/16/06, Bil K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Xavier N. wrote:
> 
> > Have a look at the regexp in
> > 
> > perldoc -q float
> 
> /^([±]?)(?=\d|.\d)\d\*(.\d\*)?(Ee)?$/
> 
> Ouch!
> 
> Thanks; I think. 🙂

Quick caveat - that’s for a c float (as mentioned in that perldoc  
snippet). Ruby float (& other numeric) literals allow the underscore  
character (with restrictions) as well. So really, it depends on  
exactly what you’re parsing and why.

-A
