尝试使用正则表达式读取命令行开关

时间:2017-04-14 15:51:11

标签: c++ regex

所以我试图从fileusage.exe [开关] [文件夹]格式的命令行读取输入,只要它们以 - 开头,就可以输入格式。例如-c + j#R。

 int main(int argc, char *argv[])

{
    cout.imbue(locale(""));

vector<char> theSwitches;
regex switches(R"reg(\-(c|\+|j|#|w|s|x|r|R|S|v|h)$)reg");

if (argc > 1)
{

    // search through the command line args and find matching switches
    if (regex_match(argv[1], switches))
    {
        theSwitches.push_back(argv[1]);
    }
    else
        cout << "Didnt find the switches" << endl;

}

1 个答案:

答案 0 :(得分:1)

使用此代码,您将能够迭代参数。我已删除$,因为它始终与参数列表的结尾匹配。

regex switches(R"reg(\-(c|\+|j|#|w|s|x|r|R|S|v|h))reg");

std::string s = "-c -S";

using reg_itr = std::regex_token_iterator<std::string::iterator>;
for (reg_itr it{s.begin(), s.end(), switches, {1}}, end{}; it != end;) {
    std::cout << *it++ << "\n";
}
// outputs:
// c
// S