这似乎是一个很容易的问题,但我在完成这个问题时遇到了麻烦。其他线程谈论匹配和RE模块,但我不能让它工作。
def get_lead_state():
print ""
lead_state = raw_input(" Enter the lead's two letter state abbreviation ")
lead_state = lead_state.upper()
if None == re.match("[AL,AK,AZ,AR,CA,CO,CT,DE,FL,GA,HI,ID,IL,IN,IA,KS,KY,LA,ME,MD,MA,MI,MN,MS,MO,MT,NE,NV,NH,NJ,NM,NY,NC,ND,OH,OK,OR,PA,RI,SC,SD,TN,TX,UT,VT,VA,WA,WV,WI,WY]", lead_state):
print ""
print " == msg ==> ERROR! abbreviation not recognized!"
print " == msg ==> Try again"
lead_state = get_lead_state()
return lead_state
出于某种原因,这允许通过ZZ或VTA等输入。我也尝试将^
放在缩写列表之前,我尝试将*
和$
放在最后。我不确定为什么我不能让这个工作。
-
另外,如果找到匹配项,为什么re.match
不返回True
答案 0 :(得分:2)
您可以使用set
这样的
valid = {"AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"}
if not lead_state.upper() in valid:
答案 1 :(得分:1)
r'[AL,AK]'表示匹配一个字符,即A,L,逗号,A,或 K等等。
只需使用查找列表:
states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI",
"ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI",
"MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT",
"VT", "VA", "WA", "WV", "WI", "WY"]
if lead_state.upper().strip() not in states:
print " == msg ==> ERROR! abbreviation not recognized!"