GUID regex Java

GUID

GUID is an acronym for Globally Unique Identifier and used for resource identification. The term is generally used instead of UUID when working with Microsoft technologies.

GUID regex

Below is a simple regular expression to match a guide in a given string:


Pattern.compile("^(?:\\{{0,1}(?:[0-9a-fA-F]){8}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){12}\\}{0,1})$")

Test it!
/^(?:\{{0,1}(?:[0-9a-fA-F]){8}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){12}\}{0,1})$/

True

False

Enter a text in the input above to see the result

Example code in Java:


import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;

public class Main {

    public static void main(String []args) {
        // Validate GUID
        boolean isMatch = Pattern.compile("^(?:\\{{0,1}(?:[0-9a-fA-F]){8}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){12}\\}{0,1})$")
               .matcher("{51d52cf1-83c9-4f02-b117-703ecb728b74}")
               .find(); 
        System.out.println(isMatch); // prints true
        
        // Extract GUID from a string
        String[] matches = Pattern.compile("(?:\\{{0,1}(?:[0-9a-fA-F]){8}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){12}\\}{0,1})")
                          .matcher("Resource {51d52cf1-83c9-4f02-b117-703ecb728b74} is down")
                          .results()
                          .map(MatchResult::group)
                          .toArray(String[]::new);
        System.out.println(Arrays.toString(matches)); // prints [{51d52cf1-83c9-4f02-b117-703ecb728b74}]
    }
}

Test it!

True

False

Enter a text in the input above to see the result

Test it!

True

False

Enter a text in the input above to see the result