如何在Python 3中使用Regex实现带特定错误提示的数据验证
Let's break this down into a straightforward, actionable solution. The goal is to not just reject bad input, but tell the user exactly what's wrong—whether it's a formatting issue or an invalid province abbreviation.
Step 1: Define Your Valid Data & Regex Pattern
First, let's set up a list of valid province abbreviations (I'll use Canadian provinces since your example mentions Alberta) and a regex pattern that matches the expected "Location, Abbreviation" format. The pattern will capture both the location name and the abbreviation so we can check them separately.
import re # List of valid Canadian province/territory abbreviations VALID_PROVINCE_ABBR = {"AB", "BC", "MB", "NB", "NL", "NT", "NS", "NU", "ON", "PE", "QC", "SK", "YT"} # Regex pattern: matches text like "Alberta, AB" or "Newfoundland and Labrador, NL" # Captures two groups: (location name), (abbreviation) INPUT_PATTERN = re.compile(r"^([A-Za-z\s]+),\s*([A-Z]{2})$")
Step 2: Build the Validation Function
Now create a function that checks the input, uses the regex to extract parts, and returns specific error messages or confirms validity.
def validate_location(input_str): # First check if the input matches the expected format match = INPUT_PATTERN.match(input_str) if not match: return "I'm sorry, your input is in an invalid format. Please use 'Location, XX' (e.g., 'Alberta, AB')." # Extract the captured groups location, abbr = match.groups() abbr_upper = abbr.upper() # Normalize to uppercase for consistent checking # Check if the abbreviation is valid if abbr_upper not in VALID_PROVINCE_ABBR: return f"I'm sorry, {abbr_upper} is an invalid province abbreviation." # If all checks pass return f"Valid input: {location}, {abbr_upper}"
Step 3: Test It Out
Let's run through some test cases to see how it works:
# Test 1: Invalid abbreviation (your example) print(validate_location("Alberta, UN")) # Output: I'm sorry, UN is an invalid province abbreviation. # Test 2: Wrong format (missing comma) print(validate_location("Alberta UN")) # Output: I'm sorry, your input is in an invalid format. Please use 'Location, XX' (e.g., 'Alberta, AB'). # Test 3: Correct input print(validate_location("British Columbia, BC")) # Output: Valid input: British Columbia, BC # Test 4: Abbreviation in lowercase print(validate_location("Ontario, on")) # Output: Valid input: Ontario, ON
Key Details to Note
- Regex Grouping: By capturing the location and abbreviation separately, we can isolate exactly which part is wrong.
- Case Normalization: Converting the abbreviation to uppercase ensures we don't reject valid inputs just because the user used lowercase (like "on" instead of "ON").
- Specific Error Messages: Instead of a generic "invalid input", we tell the user if it's a formatting issue or an invalid abbreviation—making it way easier for them to fix the problem.
You can easily adapt this to your specific use case: just update VALID_PROVINCE_ABBR to match your list of valid abbreviations, and adjust the regex pattern if your input format is slightly different (e.g., if you don't allow spaces in the location name, modify the [A-Za-z\s]+ part).
内容的提问来源于stack exchange,提问作者Empress Obazee

