繁体   English   中英

C ++ 03的正则表达式库

[英]Regular Expression Library for C++03

我有一个需要验证的这种格式的字符串:

H12345-001

在这里,第一个字符应该是字母字符,后跟5个数字,然后是破折号( - ),然后是两个零,最后是一个数字。

我不确定正则表达式是正确的选择还是可以比较每个字符的幼稚方式做到这一点。 如果正则表达式是正确的选择,那么有人可以指出示例教程来使用它。 我正在使用C ++ 03(即没有C ++ 11)。

假设您的字符串可以包含小写字母,则正则表达式为[a-zA-z]\\d\\d\\d\\d\\d-00\\d (如果您不希望使用小写字母,只需删除az )。

如果引入一个正则表达式库不值得,那么可以使用简单的自定义验证器( demo ):

bool isValid(const std::string& str)
{
    return
        (str.size() == 10) &&
        (('a' <= str[0] && str[0] <= 'z') ||
        ('A' <= str[0] && str[0] <= 'Z')) &&
        ('0' <= str[1] && str[1] <= '9') &&
        ('0' <= str[2] && str[2] <= '9') &&
        ('0' <= str[3] && str[3] <= '9') &&
        ('0' <= str[4] && str[4] <= '9') &&
        ('0' <= str[5] && str[5] <= '9') &&
        (str[6] == '-' && str[7] == '0' && str[8] == '0') &&
        ('0' <= str[9] && str[9] <= '9');
}

您可以为此使用Boost.Regex

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>

boost::regex your_regex("[A-Z]\\d{5}-00\\d");
boost::smatch match;

int main() {
    std::string input = "H12345-001";
    std::string output;
    if(boost::regex_match(input, match, your_regex)) {
        output = boost::lexical_cast<std::string>(match);
        std::cout << output << std::endl;
    } 
    return 0;
}

这是匹配单个事件的示例,您将需要对其进行调整。

任何正则表达式库都可以。 例如,有用于POISX系统的pcre,您只需#include <regex.h>并调用regcomp系列函数(有关更多信息,请#include <regex.h> man 3 regcomp )。 这些都不需要C ++ 11。

坦率地说,如果您要使用正则表达式,对于这个问题似乎不值得,那么一个困难的问题是在C ++代码中使用适当的正则表达式模式,因为必须转义所有反斜杠和其他内容。 您可能想在SO中尝试这种出色的解决方案,以便在C ++ <11中使用正则表达式时没有太大问题。

否则,请遵循Cornstalk的答案。

这个正则表达式非常糟糕,但是最容易理解的是我可以提出的正则表达式将与您想要的匹配。

([A-Z])\d\d\d\d\d-00\d

这是一个有关要求的教程: http : //en.cppreference.com/w/cpp/regex

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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