Over a million developers have joined DZone.

Determine If A String Contains Only A Whole Number In Ruby

DZone's Guide to

Determine If A String Contains Only A Whole Number In Ruby

Free Resource

string =~ /^\s*\d+\s*$/

Determines if there is one and only one substring in a string and that it is a whole number. The whole numbers are 0 and the counting numbers, in other words: 0, 1, 2, 3, and so on. No punctuation of any kind is allowed within the string, but the substring can optionally have leading whitespace, leading zeros, and trailing whitespace. 


0 True. Found match for expression at position 0.
nil False. No match found for the expression.

Explanation from left to right

Use only on strings.

is the Ruby regex match operator. 

The expression is enclosed in forward slashes to compile correctly. 

^ (circumflex or caret)
Anchor the beginning of the string. It can be replaced with \A because it's Ruby. The caret doesn't stand for negation here because it's not inside square brackets.

Stands for whitespace. 

0 or more of the preceding regular expression.

Stands for the digits zero through nine. [0-9] could have been used instead. [[:digit:]] could also have been substituted for the \d. It's POSIX 1003.2 section (6)-compliant, ugly, and little-used, but it does take "locale" into account. (What are the locales that don't use 0-9 as digits?)

1 or more of the preceding regular expression.

$ (dollar)
Anchor the end of the string. It can be replaced with \Z (or z to anchor before a newline at the end) because it's Ruby.

Determine if a string contains only a valid whole number in Ruby

string =~ /^\s*[0|^0\d+]\s*$/

This can be used for the same purpose as above except leading zeros are no longer allowed. The 0|^0 inside the square brackets accomplishes this. 

The number can be zero, the 0 in the expression, but a number of two or more digits can't start with a zero, the ^0\d+. It can be one or the other, the |. (The caret, ^, only works as negation within square brackets, [ and ]).

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}