Validating UUIDs with Regular Expressions in Java

Featured image for sharing metadata for article

Universally Unique Identifier (UUID) or UUIDs are a great way of providing practical randomness, for instance for tracking IDs or generated database keys.

I've worked with them a fair bit, and each time I end up working with them, I find myself needing to Google for the regular expression that works for Java.

In the spirit of blogumentation, I thought I'd document it for future me:

/**
 * Regular expression, in {@link String} form, to match a Universally Unique Identifier (UUID), in
 * a case-insensitive fashion.
 */
public static final String UUID_STRING =
    "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}";
/**
 * Regular expression to match any Universally Unique Identifier (UUID), in a case-insensitive
 * fashion.
 */
public static final Pattern UUID = Pattern.compile(UUID_STRING);
/**
 * Regular expression, in {@link String} form, to match a Version 4 Universally Unique Identifier
 * (UUID), in a case-insensitive fashion.
 */
public static final String UUID_V4_STRING =
    "[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[89abAB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}";
/**
 * Regular expression to match a Version 4 Universally Unique Identifier (UUID), in a
 * case-insensitive fashion.
 */
public static final Pattern UUID_V4 = Pattern.compile(UUID_V4_STRING);

These are an extract from the Apache-2.0 licensed java library uuid.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #uuid #regex.

This blog post is 100% human-written, and has nothing derived from LLMs (be it code, editorial support or prose).

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.