求助:Python中验证含自定义命名空间的URN格式UUID
The issue here is that Python's uuid module only recognizes standard UUID strings (like your x variable) or the standard URN format (urn:uuid:..., like your y variable). The custom URN (z) adds extra namespace segments (vendor:processor) which the module doesn't expect, hence the error.
Here are two reliable ways to extract and validate the UUID from your custom URN:
1. Split the URN String (Simple & Straightforward)
Since your custom URN follows the pattern urn:vendor:processor:uuid:<valid-uuid>, you can split the string on colons and grab the last segment (which is the valid UUID):
import uuid z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b" # Extract the UUID part uuid_str = z.split(':')[-1] # Validate it try: valid_uuid = uuid.UUID(uuid_str) print(f"Valid UUID: {valid_uuid}") except ValueError: print("Invalid UUID format")
This works because splitting on colons gives you a list like ['urn', 'vendor', 'processor', 'uuid', '0269803d-50c4-46b0-9f50-60ef7fe3e22b'], and the last element is the UUID you need.
2. Use Regular Expressions (Robust for Variable Structures)
If you need to handle cases where the URN structure might vary slightly (but the UUID is always in the standard dashed format), use a regex to match the UUID pattern directly:
import uuid import re z = "urn:vendor:processor:uuid:0269803d-50c4-46b0-9f50-60ef7fe3e22b" # Regex pattern for standard UUIDs (dashed format) uuid_pattern = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.IGNORECASE) # Find the UUID match match = uuid_pattern.search(z) if match: uuid_str = match.group() try: valid_uuid = uuid.UUID(uuid_str) print(f"Valid UUID: {valid_uuid}") except ValueError: print("Invalid UUID format") else: print("No UUID found in the string")
This regex will find any valid dashed UUID in the string, regardless of what comes before it.
Why This Works
The uuid.UUID() constructor accepts:
- A 32-character hex string (no dashes, like
x) - A 36-character dashed string (like the one we extract from
z) - The standard
urn:uuid:...format (likey)
By extracting just the UUID part from your custom URN, you're giving the module exactly what it expects to validate.
内容的提问来源于stack exchange,提问作者Guts

