I’m trying to write a small program that asks a user to input a number and the program will determine if it’s a valid number. The user can enter any kind of number (integer, float, scientific notation, etc.).
My question is what regular expression should be used to keep something like “7w” from being matched as a valid number? Also I would like the number 0 to exit the loop and end the program, but as it’s written now 0 is matching valid like any other number. Any insight please?
x = 1
while x != 0
puts "Enter a string"
num = gets
if num.match(/\d+/)
puts "Valid"
else
puts "invalid"
end
if num == 0
puts "End of program"
x = num
end
end
To start with, you are overcomplicating the loop, secondly, your regular expression needs to be a bit more explicit. Try something like this:
This expression will match any number that contains a digit or a decimal, and will fail to match anything containing letters. If the string entered is exactly 0, the script will exit with status 0.