Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regular expression to validate user input is an integer

Tags:

python

regex

I am trying to validate a user's input. I only want the user to be able to enter a positive or negative integer. All other inputs (i.e. anything with letters) should be rejected

I have the code below at the minute, however I am getting an error. I'm assuming it has to do with the data types but am unsure how to fix this.

import re

number =input("Please enter a number: ")
number=int(number)
while not re.match("^[0-9 \-]+$", number):
    print ("Error! Make sure you only use numbers")
    number = input("Please enter a number: ")
print("You picked number "+ number)
like image 704
Miss Jones Avatar asked Feb 28 '26 17:02

Miss Jones


1 Answers

If all you care about is that the input was a valid numeric literal, don't even bother with the regexp. int will correctly parse the string or raise an exception.

while True:
    s = input("Please enter a number: ")
    try:
        n = int(s)
        break
    except ValueError:
        print("Error! Make sure you only use numbers")
print("You picked number " + n)
like image 108
jpkotta Avatar answered Mar 03 '26 06:03

jpkotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!