简体   繁体   中英

Alternative way of using regex for Visual Studio 2003

I built a example program to check a value with regex. This example is running up on Visual Studio 2012.

But the Regex doesn't exist on Visual Studio 2003.

My Question is: How can I check a value with a Visual Studio 2003 without using the Regex and 3rd parties library?

My Source-Code:

#include "stdafx.h"
#include <regex>
#include <string>
using namespace std;


int main()
{
    std::string code1 = "{1N851111-8M32-2234-B83K-123456789012}";
    std::regex control("^[{]{8}[A-Za-z0-9]{1}[-]{4}[A-Za-z0-9]{1}[-]{4}[A-Za-z0-9]{1}[-]{4}[A-Za-z0-9]{1}[-]{12}[A-Za-z0-9]$[}]");
    std::smatch match;

    if (std::regex_search(code1, match, control))
    {
        std::cout << "MAtch found";

    }

    else
    {
        std::cout << "Match not found";
    }

    return 0;
}

Well, if you do not want to use third party libraries (why, by the way?), you will have to go all the way by foot... (Sounds easy, doesn't it?)

At very first, your regex does not seem to be what you are after. Have you tried it? This one, at least, matches your example string:

std::regex control("^[{][A-Za-z0-9]{8}([-][A-Za-z0-9]{4}){3}[-][A-Za-z0-9]{12}[}]$");

Then let's have a look at the regex (I'm going to use mine...):

^ – fine, right from the start, so we do not have to search somewhere in the middle of the string...
[{] – must be an opening brace
[A-Za-z0-9]{8} – followed by exactly eight alphanumeric characters
([-][A-Za-z0-9]{4}){3} – a minus sign followed by for alphanumerics – the whole stuff three times
[-][A-Za-z0-9]{12} – another minus followed by telve alphanumerics
[}]$ – closing brace at the end

So:

bool isValid(::std::string const& value)
{
    if(value.length() != 38)
        return false;
    char const* v = value.c_str();
    if(*v++ != '{')
        return false;
    for(char const* end = v + 8; v != end; ++v)
    {
        if(!isalnum(*v))
            return false;
    }
    for(int i = 0; i < 3; ++i)
    {
        if(*v++ != '-')
            return false;
        for(char const* end = v + 4; v != end; ++v)
        {
            if(!isalnum(*v))
                return false;
        }
    }
    if(*v++ != '-')
        return false;
    for(char const* end = v + 12; v != end; ++v)
    {
        if(!isalnum(*v))
            return false;
    }
    return *v == '}';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM