# Regular Expression Question

**URL:** <https://www.ruby-forum.com/t/regular-expression-question/92205>\
**Category:** Ruby\
**Created:** [April 17, 2007, 2:56am UTC](https://www.ruby-forum.com/t/regular-expression-question/92205 "2007-04-17T02:56:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 17, 2007, 2:56am UTC](https://www.ruby-forum.com/t/regular-expression-question/92205/1 "2007-04-17T02:56:05Z")

</div>

I have been reading _The Ruby Way_ and am confused by the temperature  
conversion sample program on page 14.

The line in question is

abort “#{temp} is not a valid number.” if temp !~ /-?\d+/

What I do not understand is that if \d matches “digits”, which I  
understand to be [0-9], how can this expression match “98.6”, which it  
seems to do just fine.

Thank you in advance for the clarification.

(I have the 2nd Edition of _The Ruby Way_, First Printing. I have run  
the example using ruby 1.8.5 (2007-03-13 patchlevel 35) [i386-linux]).

Matt

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 17, 2007, 3:54am UTC](https://www.ruby-forum.com/t/regular-expression-question/92205/2 "2007-04-17T03:54:07Z")

</div>

From: “removed\_email\_address@domain.invalid” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

> seems to do just fine.  
> Hi,

Since that regexp isn’t anchored, it only cares whether a digit  
appears anywhere in the string.

It would be happy with “abc1def”.

If you anchor it, like: /\A-?\d+\z/

Then it will require an exact match, caring about all characters  
between the beginning and end of the string.

Hope this helps,

Bill

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 17, 2007, 9:48pm UTC](https://www.ruby-forum.com/t/regular-expression-question/92205/3 "2007-04-17T21:48:22Z")

</div>

On 4/17/07, removed\_email\_address@domain.invalid [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Thank you in advance for the clarification.  
> Well I guess you are a bright student.  
> The regexp part has been nicely answered by Bill and it follows that a  
> regular expression allowing for all kind of different string  
> representations of Floats is quite  
> complex.  
> Why not let ruby do the work for us 😉  
> May I introduce you to this idiom:

Float( temp ) rescue abort temp \<\< " is not a valid number."

Cheers  
Robert
