Regex to Validate UUIDs

Get the definitive regex pattern for validating UUIDs. Covers strict validation by version, case-insensitive matching, and common regex pitfalls to avoid.

Format

Detailed Explanation

Validating UUIDs with regular expressions is a common task in input validation, log parsing, and data cleaning. The right regex depends on how strict your validation needs to be.

General UUID regex (any version):

^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$

This matches the 8-4-4-4-12 hex format but does not validate version or variant bits. Use the i flag for case-insensitive matching.

Strict RFC-compliant regex (versions 1-7 with correct variant):

^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

This checks that the version digit (first hex of group 3) is 1-7 and the variant digit (first hex of group 4) is 8, 9, a, or b.

Version-specific regexes:

// UUID v4 only
^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

// UUID v7 only
^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

Including Nil and Max UUIDs: If your validation should accept the Nil UUID (00000000-0000-0000-0000-000000000000) and Max UUID (ffffffff-ffff-ffff-ffff-ffffffffffff), the strict regex above will reject them because their version and variant bits do not match. Handle them as special cases:

function isValidUuid(str) {
  if (str === '00000000-0000-0000-0000-000000000000') return true;
  if (str === 'ffffffff-ffff-ffff-ffff-ffffffffffff') return true;
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-7][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str);
}

Common pitfalls:

  1. Forgetting case-insensitivity: UUIDs are case-insensitive. Always use the i flag or include A-F in character classes.
  2. Matching without anchors: Without ^ and $, the regex can match UUIDs embedded in longer strings.
  3. Rejecting valid formats: Some systems output UUIDs without hyphens or in URN format (urn:uuid:...). Decide what formats to accept.
  4. Over-validating: For most applications, the general format check is sufficient. Version/variant validation is only needed when you must guarantee RFC compliance.

Performance note: For high-volume validation (parsing millions of log lines), a simple length + character check can be faster than regex: verify length is 36, hyphens at positions 8, 13, 18, 23, and all other characters are hex digits.

Use Case

UUID regex validation is essential in API input sanitization to prevent injection attacks and ensure that user-supplied identifiers conform to the expected format before database lookups.

Try It — UUID Generator

Open full tool