0

I'm trying to prompt the user to input a data value, and check that the string they enter only contains the digits 0-9:

class String
    def validate(regex)
        !self[regex].nil?
    end
end

regex = /\A[0-9]\z/

validInput = false
until validInput
    puts "Enter digits: "
    input = gets.chomp
    if !input.validate(regex)
        puts "Invalid input. Seeking integer."
    else
        validInput = true

    end
end

However this loop returns false on everything other than single digits excluding 0. I previously had this working with regex = /\A[1-9]\z/, but I going back to where it was working, it doesn't anymore, and this also means the user can't enter 0.

How can I use a regex to validate that user input only contains the digits 0-9?

1
  • Why are those new to SO in such a rush to select an answer? Take it easy. Give it some time. There's no rush. You don't want to discourage other answers and have some consideration for members still working on their answers. Commented Jun 29, 2015 at 6:45

2 Answers 2

2

Add a + quantifier after [1-9](Shouldn't it be [0-9] is you want digits from 0 to 9?). i.e. regex = /\A[0-9]+\z/

You can represent the character class [0-9] as \d so that the regex looks neater: \A\d+\z

The + checks for one(minimum) or more occurrences of a digit in the string. Right now, you are checking for presence of only ONE digit.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for this :) Accept in 7 mins
@AvinashRaj OP asked for "regex to validate that user input only contains the digits 0-9?"
/\A[0-9]+\z/ is customarily written /\A\d+\z/.
How can I extend this to include a single decimal point (.)? So the user can enter 10.2 but not 10.2.2 or 10..2
@Nemo Modify it to \A[0-9]+(\.[0-9]+)?\z, here the ? is a quantifier that matches for either no occurrence or one occurrence. \A\d+(\.\d+)?\z looks neater though. :)
|
1
s !~ /\D/

.....................

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.