简体   繁体   English

使用正则表达式验证用户输入是一个整数

[英]Using regular expression to validate user input is an integer

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 (ie 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)

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. int将正确解析字符串或引发异常。

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)

Regular expressions need strings as input, not numbers. 正则表达式需要字符串作为输入,而不是数字 Thus, you do not have to cast the string to number, and you can omit number=int(number) . 因此,您不必将字符串强制转换为数字,并且可以省略number=int(number)

Here is a working demo : 这是一个有效的演示

number = "2"
if not re.match("^[0-9 -]+$", number):
    print ("Error! Make sure you only use numbers")
print("You picked number "+ number)
import re

while  True:
    number =input("Please enter a number: ")
       # number=int(number) -- This raise an error, for regexp you need use "str"

    #while not re.match("^[0-9 \-]+$", number):
    # in [0-9 \-]  after 9 you use whitespace
    # Also in [0-9 \-]  if minus at the and, not need use backslash

if  re.match("-?\d+$", number) : # minus may be only in first position
    break

print ("Error! Make sure you only use numbers")
    # deleted     number = input("Please enter a number: ")

print("You picked number "+ number)
answer = input(" ")#asks the user for an answer
ansnum = re.match("[0-9 \-]",answer)#checks to see if answer only contains numbers
while not ansnum: #whilst the answer does not contain numbers do....
   answer = input("Enter numbers as your answer: ")#asks the user for a valid answer
   ansnum = re.match("[0-9 \-]",answer)#checks to see if the answer contains numbers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM