use*_*420 2 python validation user-input
在python中,我要求用户输入一个办公室代码位置,该位置需要采用以下格式:XX-XXX(其中X将是字母)
如何确保他们的输入符合格式,如果它不要求他们再次输入办公室代码?
谢谢!
标准(和语言无关)的方法是使用正则表达式:
import re
re.match('^[0-9]{2}-[0-9]{3}$', some_text)
Run Code Online (Sandbox Code Playgroud)
如果文本包含2位数,连字符和3个其他数字,则上面的示例返回True(实际上,"truthy"返回值,但您可以假装它True).以上是正则表达式的细分部分:
^ # marks the start of the string
[0-9] # any character between 0 and 9, basically one of 0123456789
{2} # two times
- # a hyphen
[0-9] # another character between 0 and 9
{3} # three times
$ # end of string
Run Code Online (Sandbox Code Playgroud)
我建议你阅读更多关于正则表达式(或re,或正则表达式,或正则表达式,但你想要命名),它们是程序员的某种瑞士军刀.