首页 > 解决方案 > 如何使用正则表达式和 python 3 获取特定的错误消息到数据验证

问题描述

我如何获得如下示例的特定输出:

示例 1 - 如果用户输入Alberta, UN。我希望能够看到打印结果,对不起,UN 是无效的省级缩写。 如果程序可以显示与用户输入相关的确切错误,我会很高兴。而不是一个错误说对不起,这是一个错误,没有任何具体的消息让用户知道他/她的错在哪里。

如果我能得到一些结果,我将不胜感激,因为我一直在集思广益如何让它发挥作用

# Import
import re

# Program interface
print("====== POSTAL CODE CHECKER PROGRAM ====== ")
print("""
Select from below city/Province and enter it
--------------------------------------------
Alberta, AB,
British Columbia, BC
Manitoba, MB
New Brunswick, NB
Newfoundland, NL
Northwest Territories, NT
Nova Scotia, NS
Nunavut, NU
Ontario, ON
Prince Edward Island, PE
Quebec, QC
Saskatchewan, SK
Yukon, YT
""")

# User input 1
province_input = input("Please enter the city/province: ")

pattern = re.compile(r'[ABMNOPQSYabcdefhiklmnorstuvw]| [CBTSE]| [Idasln], [ABMNOPQSY]+[BCLTSUNEK]')

if pattern.match(province_input):
    print("You have successfully inputted {} the right province.".format(province_input))
elif not pattern.match(province_input):
    print("I'm sorry, {} is an invalid province abbreviation".format(province_input))
else:
    print("I'm sorry, your city or province is incorrectly formatted.")

标签: regexpython-3.xvalidationif-statement

解决方案


我试图概括您的问题,因此它将检查输入的第一部分是否为有效城市,第二部分是否为有效的州缩写,当“有效”表示它们中的每一个都出现在其相关的有效输入列表中时。

代码的核心是正则表达式 ([A-Z][A-Za-z ]+), ([A-Z]{2}),它匹配两组:第一组包含城市 - 在逗号和空格之后 - 第二组包含州缩写(必须包含两个大写字母)。

请注意,根据每个部分的有效性,有 5 种可能的输出。

import re

cities = ["Alberta", "British Columbia", "Manitoba"]
states = ["AB", "BC", "MB"]

province_input = input("Please enter the city/province: ")
regexp = r"([A-Z][A-Za-z ]+), ([A-Z]{2})"

if re.compile(regexp).match(province_input):
    m = re.search(regexp, province_input)
    city_input = m.group(1)
    state_input = m.group(2)
    if city_input not in cities and state_input not in states:
        print("Both '%s' and '%s' are valid" % (city_input, state_input))
    elif city_input in cities:
        if state_input in states:
            print("Your input '%s, %s' was valid" % (city_input, state_input))
        else:
            print("'%s' is an invalid province abbreviation" % state_input)
    else:
        print("The city '%s' is invalid" % city_input)
else:
    print("Wrong input format")

我试图使代码尽可能清晰,但如果有任何不清楚的地方,请告诉我。


推荐阅读