Parsing GUID in C++ with a regular expression

The code below demonstrates how to parse GUID in C++ using a regular expression:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    static const std::wregex regex(L"[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}");
    
    std::wstring sample = L"850fe1da-0ea6-c1a8-9810-0c1cece30698";

    std::match_results<std::wstring::const_iterator> match;

    if (std::regex_match(sample, match, regex))
    {
        std::wcout << L"matches" << std::endl;
    }
    else
    {
        std::wcout << L"does not match" << std::endl;
    }

    return 0;
}

The code can be compiled with MS VS using the following command:

cl /std:c++17 /EHsc a.cpp

The example below parses GUID along with a date and time:

#include <iostream>
#include <string>
#include <regex>

int main()
{
    static const std::wregex regex(L".*\\\\([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})\\\\SomeSubdir\\\\SomePrefix_([0-2][0-9][0-9][0-9])([0-1][0-9])([0-3][0-9])\\-([0-1][0-9])([0-5][0-9])([0-5][0-9])\\.dat");
    
    const std::wstring sample = L"ProgramData\\MyApp\\Data\5e1e02b0-a011-4f51-8bad-9775c15235b3\\f7da40c1-b340-4bbc-8cdd-45656d1013a0\\SomeSubdir\\SomePrefix_20190714-015315.dat";

    std::wcmatch match;

    if (std::regex_match(sample.c_str(), match, regex))
    {
        std::wcout << L"matches" << std::endl;

        std::wcout << L"the number of matches is " << match.size() << std::endl;

        if (match.size() == 8)
        {
            int year = std::stoi(match[2].str());
            int month = std::stoi(match[3].str());
            int day = std::stoi(match[3].str());
            int hour = std::stoi(match[4].str());
            int minute = std::stoi(match[5].str());
            int second = std::stoi(match[6].str());

            std::wcout << L"GUID: " << match[1].str() << L", date: " << year << '-'<< month << '-' << day << ' ' << hour << ':' << minute << ':' << second << std::endl;
        }
    }
    else
    {
        std::wcout << L"does not match" << std::endl;
    }

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *