Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
How to validate GUID (Globally Unique Identifier) using Regular Expression
Next article icon

How to validate GUID (Globally Unique Identifier) using Regular Expression

Last Updated : 19 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given string str, the task is to check whether the given string is a valid GUID (Globally Unique Identifier) or not by using Regular Expression.
The valid GUID (Globally Unique Identifier) must specify the following conditions: 

  1. It should be a 128-bit number.
  2. It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.
  3. It should be displayed in five groups separated by hyphens (-).
  4. Microsoft GUIDs are sometimes represented with surrounding braces.

Examples: 

Input: str = "123e4567-e89b-12d3-a456-9AC7CBDCEE52" 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions. Therefore, it is a valid GUID (Globally Unique Identifier).
Input: str = "123e4567-h89b-12d3-a456-9AC7CBDCEE52" 
Output: false 
Explanation: 
The given string contains 'h', the valid hexadecimal characters should be followed by character from a-f, A-F, and 0-9. Therefore, it is not a valid GUID (Globally Unique Identifier).
Input: str = "123e4567-h89b-12d3-a456" 
Output: false 
Explanation: 
The given string has 20 characters. Therefore, it is not a valid GUID (Globally Unique Identifier). 

Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:

  • Get the String.
  • Create a regular expression to check valid GUID (Globally Unique Identifier) as mentioned below:
     

regex = "^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$" 

  • Where: 
    • ^ represents the starting of the string.
    • [{]? represents the '{' character that is optional.
    • [0-9a-fA-F]{8} represents the 8 characters from a-f, A-F, and 0-9.
    • - represents the hyphens.
    • ([0-9a-fA-F]{4}-){3} represents the 4 characters from a-f, A-F, and 0-9 that is repeated 3 times separated by a hyphen (-).
    • [0-9a-fA-F]{12} represents the 12 characters from a-f, A-F, and 0-9.
    • [}]? represents the '}' character that is optional.
    • $ represents the ending of the string.
  • Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().
  • Return true if the string matches with the given regular expression, else return false.


Below is the implementation of the above approach:
 

C++
// C++ program to validate the // GUID (Globally Unique Identifier) using Regular Expression #include <iostream> #include <regex> using namespace std;  // Function to validate the GUID (Globally Unique Identifier). bool isValidGUID(string str) {    // Regex to check valid GUID (Globally Unique Identifier).   const regex pattern("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");     // If the GUID (Globally Unique Identifier)   // is empty return false   if (str.empty())   {      return false;   }    // Return true if the GUID (Globally Unique Identifier)   // matched the ReGex   if(regex_match(str, pattern))   {     return true;   }   else   {     return false;   } }  // Driver Code int main() {   // Test Case 1:   string str1 = "123e4567-e89b-12d3-a456-9AC7CBDCEE52";   cout << isValidGUID(str1) << endl;    // Test Case 2:   string str2 = "{123e4567-e89b-12d3-a456-9AC7CBDCEE52}";   cout <<  isValidGUID(str2) << endl;    // Test Case 3:   string str3 = "123e4567-h89b-12d3-a456-9AC7CBDCEE52";   cout <<  isValidGUID(str3) << endl;    // Test Case 4:   string str4 = "123e4567-h89b-12d3-a456";   cout <<  isValidGUID(str4) << endl;    return 0; }  // This code is contributed by yuvraj_chandra 
Java
// Java program to validate // GUID (Globally Unique Identifier) // using regular expression  import java.util.regex.*;  class GFG {      // Function to validate     // GUID (Globally Unique Identifier)     // using regular expression     public static boolean     isValidGUID(String str)     {         // Regex to check valid         // GUID (Globally Unique Identifier)         String regex             = "^[{]?[0-9a-fA-F]{8}"               + "-([0-9a-fA-F]{4}-)"               + "{3}[0-9a-fA-F]{12}[}]?$";          // Compile the ReGex         Pattern p = Pattern.compile(regex);          // If the string is empty         // return false         if (str == null) {             return false;         }          // Find match between given string         // and regular expression         // uSing Pattern.matcher()          Matcher m = p.matcher(str);          // Return if the string         // matched the ReGex         return m.matches();     }      // Driver code     public static void main(String args[])     {          // Test Case 1:         String str2             = "123e4567-e89b-12d3"               + "-a456-9AC7CBDCEE52";         System.out.println(             isValidGUID(str2));          // Test Case 2:         String str3             = "{123e4567-e89b-12d3-"               + "a456-9AC7CBDCEE52}";         System.out.println(             isValidGUID(str3));          // Test Case 3:         String str1             = "123e4567-h89b-12d3-a456"               + "-9AC7CBDCEE52";         System.out.println(             isValidGUID(str1));          // Test Case 4:         String str4             = "123e4567-h89b-12d3-a456";         System.out.println(             isValidGUID(str4));     } } 
Python3
# Python3 program to validate  # GUID (Globally Unique Identifier)  # using regular expression import re  # Function to validate GUID  # (Globally Unique Identifier)  def isValidGUID(str):      # Regex to check valid      # GUID (Globally Unique Identifier)      regex = "^[{]?[0-9a-fA-F]{8}" + "-([0-9a-fA-F]{4}-)" + "{3}[0-9a-fA-F]{12}[}]?$"              # Compile the ReGex     p = re.compile(regex)      # If the string is empty      # return false     if (str == None):         return False      # Return if the string      # matched the ReGex     if(re.search(p, str)):         return True     else:         return False  # Driver code  # Test Case 1: str1 = "123e4567-e89b-12d3" + "-a456-9AC7CBDCEE52" print(isValidGUID(str1))  # Test Case 2: str2 = "{123e4567-e89b-12d3-" + "a456-9AC7CBDCEE52}" print(isValidGUID(str2))  # Test Case 3: str3 = "123e4567-h89b-12d3-a456" + "-9AC7CBDCEE52" print(isValidGUID(str3))  # Test Case 4: str4 = "123e4567-h89b-12d3-a456" print(isValidGUID(str4))  # This code is contributed by avanitrachhadiya2155 
C#
// C# program to validate // GUID (Globally Unique Identifier) using Regular Expression using System; using System.Text.RegularExpressions; class GFG {    // Main Method   static void Main(string[] args)   {      // Input strings to Match     //GUID (Globally Unique Identifier)       string[] str={"123e4567-e89b-12d3-a456-9AC7CBDCEE52","{123e4567-e89b-12d3-a456-9AC7CBDCEE52}","123e456-h89b-12d3-a456-9AC7CBDCEE52","123e4567-h89b-12d3-a456"};     foreach(string s in str) {       Console.WriteLine( isValidGUID(s) ? "true" : "false");      }     Console.ReadKey(); }    // method containing the regex   public static bool isValidGUID(string str)   {     string strRegex = @"^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$";     Regex re = new Regex(strRegex);     if (re.IsMatch(str))       return (true);     else       return (false);   } }  // This code is contributed by Rahul Chauhan 
JavaScript
// Javascript program to validate // GUID (Globally Unique Identifier) using Regular Expression  // Function to validate the // GUID   function isValidGUID(str) {     // Regex to check valid     // GUID       let regex = new RegExp(/^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$/);      // if str      // is empty return false     if (str == null) {         return "false";     }      // Return true if the str     // matched the ReGex     if (regex.test(str) == true) {         return "true";     }     else {         return "false";     } }  // Driver Code // Test Case 1: let str1 =  "123e4567-e89b-12d3"               + "-a456-9AC7CBDCEE52"; console.log(isValidGUID(str1));  // Test Case 2: let str2 = "{123e4567-e89b-12d3-"               + "a456-9AC7CBDCEE52}"; console.log(isValidGUID(str2));  // Test Case 3: let str3 =  "123e4567-h89b-12d3-a456"               + "-9AC7CBDCEE52"; console.log(isValidGUID(str3));  // Test Case 4: let str4 = "123e4567-h89b-12d3-a456"; console.log(isValidGUID(str4));   // This code is contributed by Rahul Chauhan 

Output: 
true true false false

 

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)  


Next Article
How to validate GUID (Globally Unique Identifier) using Regular Expression

P

prashant_srivastava
Improve
Article Tags :
  • Strings
  • Pattern Searching
  • DSA
  • java-regular-expression
  • CPP-regex
  • regular-expression
Practice Tags :
  • Pattern Searching
  • Strings

Similar Reads

    How to validate ISIN using Regular Expressions
    ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
    6 min read
    How to validate CVV number using Regular Expression
    Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
    5 min read
    How to validate a Username using Regular Expressions in Java
    Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or
    3 min read
    How to validate pin code of India using Regular Expression
    Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin cod
    6 min read
    How to validate image file extension using Regular Expression
    Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It shou
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences