簡體   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