Visual Studio 2003使用regex的另一种方法

Alternative way of using regex for Visual Studio 2003

本文关键字:另一种 方法 regex 使用 Studio 2003 Visual      更新时间:2023-10-16

我构建了一个使用regex检查值的示例程序。此示例正在Visual Studio 2012上运行。

但是Regex在VisualStudio2003上并不存在。

我的问题是:在不使用Regex和第三方库的情况下,如何使用Visual Studio 2003检查值?

我的源代码:

#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;
}

好吧,如果你不想使用第三方图书馆(为什么,顺便说一句?),你将不得不一路步行。。。(听起来很简单,不是吗?)

一开始,您的正则表达式似乎并不是您想要的。你试过了吗?至少,这个字符串与您的示例字符串匹配:

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

然后让我们看看正则表达式(我将使用我的…):

^–好吧,从一开始就好,所以我们不必搜索字符串中间的某个地方
[{]–必须是左大括号
[A-Za-z0-9]{8}–后面正好跟八个字母数字字符
([-][A-Za-z0-9]{4}){3}–后面跟着减号的字母数字符号–整个东西三次
[-][A-Za-z0-9]{12}–后面跟着telve字母数字的另一个减号
[}]$–末端的闭合支架

因此:

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 == '}';
}