如何验证字符串是否匹配指定格式的字符串插值?
Validate Target String Against Interpolated Format with Regex Constraints
Great question! Let's break down how to validate your target string against that specific interpolated format, including the regex constraints for UUID and date. Here's a practical, step-by-step approach:
Step 1: Break Down the Template Structure
First, split your example template into fixed text segments and variable placeholders:
- Fixed start:
s"Hello - Between name and UUID:
, Your order - Between UUID and date:
will be shipped on - Fixed end:
."
The variables we need to validate are:
${name}: Since you didn't specify constraints for this, we'll assume it can be any non-empty sequence that doesn't break the template (i.e., no}characters, as that would close the placeholder early)${UUID}: Standard UUID v4 format (matching your example; we'll adjust if you need support for other versions)${date}: Your example shows a full ISO 8601 timestamp with milliseconds and timezone, but your description mentions+%Y-%m-%dT%H:%M:%S(no milliseconds/timezone). We'll cover both options below.
Step 2: Define Regex Patterns for Each Variable
Here are the regex patterns tailored to your requirements:
- Name:
[^}]+(matches any non-empty sequence except}to avoid breaking the placeholder structure) - UUID v4:
[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(enforces v4 version and variant rules; add a case-insensitive flag if UUIDs can be uppercase) - Date (basic, no ms/timezone):
\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(matchesYYYY-MM-DDTHH:MM:SS) - Date (full ISO 8601, matches your example):
\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}[+-]\d{2}:\d{2}(includes milliseconds and timezone offset)
Step 3: Build the Full Validation Regex
Combine the fixed text segments with the variable regex patterns, escaping regex-special characters (like $ and ") in the fixed parts. Use ^ and $ to ensure the entire string matches the template (no extra characters before/after).
Example Implementation (Python)
import re # Define variable patterns name_regex = r'[^}]+' uuid_regex = r'[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}' # Choose either date regex based on your actual needs date_regex_v1 = r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}' # Basic format date_regex_v2 = r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}[+-]\d{2}:\d{2}' # Full ISO format # Build full validation pattern full_validation_pattern = re.compile( r'^s"Hello \${' + name_regex + r'} , Your order \${' + uuid_regex + r'} will be shipped on \${' + date_regex_v2 + r'}\."$', re.IGNORECASE # Allows uppercase letters in UUID ) # Test with your example string test_string = 's"Hello Alice , Your order 834aa5fd-af26-416d-b715-adca01a866c4 will be shipped on 2018-03-19T16:14:46.191+01:00."' match_result = full_validation_pattern.match(test_string) if match_result: print("✅ String matches the template!") # Extract actual variable values extracted_name = match_result.group(1) extracted_uuid = match_result.group(2) extracted_date = match_result.group(3) print(f"Extracted values:\n- Name: {extracted_name}\n- UUID: {extracted_uuid}\n- Date: {extracted_date}") else: print("❌ String does NOT match the template.")
Key Adjustments for Your Use Case
- Name Constraints: If
namehas specific rules (e.g., only letters/numbers), replace[^}]+with a more restrictive regex like[a-zA-Z0-9_]+. - UUID Versions: To support any UUID version (not just v4), use the generic regex:
[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}. - Whitespace Flexibility: If the template allows variable whitespace (e.g., multiple spaces), replace fixed spaces with
\s+(one or more spaces) or\s*(zero or more spaces).
内容的提问来源于stack exchange,提问作者Raymond Chenon
相关产品推荐
相关产品推荐

