【问题标题】:Regex is not validating date correctly正则表达式未正确验证日期
【发布时间】:2012-03-21 13:27:25
【问题描述】:
 def chkDay(x, size, part):
     dayre = re.compile('[0-3][0-9]') # day digit 0-9
     if (dayre.match(x)):
         if (len(x) > size):
             return tkMessageBox.showerror("Warning", "This "+ part +" is invalid")
             app.destroy
         else:
             tkMessageBox.showinfo("OK", "Thanks for inserting a valid "+ part)
     else:
         tkMessageBox.showerror("Warning", part + " not entered correctly!")
         root.destroy

#when clicked
chkDay(vDay.get(),31, "Day")

#interface of tkinter
vDay = StringVar()
Entry(root, textvariable=vDay).pack()

问题:

  • 没有验证,我可以输入大于 31 的一天,它仍然显示:OK
  • 当我调用 root.destroy 时,root(应用程序)没有关闭

【问题讨论】:

  • 如何使用code停止tk应用?
  • if x.isdigit() and int(x) <= size: print 'yup, correct input.'
  • 在您使用len 的代码中,您确定不是要放入int 吗? len('99') 是 2,小于 31,所以它会通过你的测试。
  • root.destroy 应该是 root.destroy()。没有括号,您就不会调用该方法。
  • 你有app.destroyroot.destroy,都没有括号。但是approot 是哪个?

标签: python regex validation tkinter


【解决方案1】:

使用正则表达式验证日期很难。您可以使用以下模式:http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1

或来自http://answers.oreilly.com/topic/226-how-to-validate-traditional-date-formats-with-regular-expressions/

请记住,检查年份是否为闰特别困难,例如日期 2011-02-29 是否有效?

我认为最好使用专门的函数来解析和验证日期。您可以使用来自datetime 模块的strptime()

【讨论】:

  • +1 :正则表达式非常方便,但不是所有的。请改用datetime 模块。
【解决方案2】:

让标准的datetime 库处理您的日期时间数据以及解析:

import datetime

try:
    dt = datetime.datetime.strptime(date_string, '%Y-%m-%d')
except ValueError:
    # insert error handling
else:
    # date_string is ok, it represents the date stored in dt, now use it

【讨论】:

    【解决方案3】:

    31 实际上在您的正则表达式中,因为 [0-3][0-9] 并不是您要查找的内容。 您最好尝试将其转换为 int 并明确检查其边界。 否则,正确的正则表达式将是 ([0-2]?\d|3[01]) 以匹配从 0 到 31 的数字

    【讨论】:

    • 我想使用正则表达式,这样用户就不能输入字母,只能输入数字。
    • 当您尝试转换为整数时会自动处理该问题;如果有字母,那将引发一个ValueError(因为输入不能解释为整数),然后您可以处理它。
    • 或者,如果您想避免捕获ValueError,只需执行if not x.isdigit() or int(x) > size: print 'bad input!'
    【解决方案4】:

    为了将值限制在 1 到 31 之间,您可以使用:

    [1-9]|[12][0-9]|3[01]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多