DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Determine If A String Contains Only A Whole Number In Ruby
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. <b>Returns</b> <b>0</b> True. Found match for expression at position 0. <b>nil</b> False. No match found for the expression. <b>Explanation</b> from left to right <b>string</b> Use only on strings. <b>=~</b> is the Ruby regex match operator. <b>/</b> The expression is enclosed in forward slashes to compile correctly. <b>^</b> (circumflex or caret) Anchor the beginning of the string. It can be replaced with <b>\A</b> because it's Ruby. The caret doesn't stand for negation here because it's not inside square brackets. <b>\s</b> Stands for whitespace. <b>*</b> 0 or more of the preceding regular expression. <b>\d</b> Stands for the digits zero through nine. <b>[0-9]</b> could have been used instead. <b>[[:digit:]]</b> could also have been substituted for the <b>\d</b>. It's POSIX 1003.2 section 18.104.22.168 (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?) <b>+</b> 1 or more of the preceding regular expression. <b>$</b> (dollar) Anchor the end of the string. It can be replaced with <b>\Z</b> (or <b>z</b> to anchor before a newline at the end) because it's Ruby. <b>Determine if a string contains only a valid whole number in Ruby</b>
string =~ /^\s*[0|^0\d+]\s*$/
This can be used for the same purpose as above except leading zeros are no longer allowed. The <b>0|^0</b> inside the square brackets accomplishes this. The number can be zero, the <b>0</b> in the expression, but a number of two or more digits can't start with a zero, the <b>^0\d+</b>. It can be one or the other, the <b>|</b>. (The caret, <b>^</b>, only works as negation within square brackets, <b>[</b> and <b>]</b>).