regex_match()之后的冗余空行

时间:2013-11-02 02:09:52

标签: c++ regex

我正在使用我的miniSQL并尝试使用正则表达式来解析用户输入。

我未能处理'create table myTable(c char(20))'的情况。如下所示,第二行和第三行是不需要的。我只是想知道他们为什么会出现在结果中。

这是我的代码:

void onCreateTable(const smatch& cmd);

int main()
{
    std::string cmd = " create table a(c char(20))";
    regex pattern;
    smatch result;
    pattern = regex("\\s*create\\s+table\\s+(\\w+)\\s*\\((.*)\\)\\s*", regex::icase);
    if  ( regex_match(cmd, result, pattern) )
    {
        onCreateTable( result );
    }

    int x; cin >> x;
    return 0;
}

void onCreateTable( const smatch& cmd )
{
    cout << "onCreateTable" << endl;
    string tableName = cmd[1];
    string attr = cmd[2];
    regex pattern = regex("\\s*(\\w+\\s+int)|(\\w+\\s+float)|(\\w+\\s+char\\(\\d+\\))",     regex::icase);
    // which will print redundant blank lines

    // while the below one will print the exact result 
    // regex pattern = regex("\\s*(\\w+\\s+char\\(\\d+\\))", regex::icase);
    smatch result;
    if ( regex_match(attr, result, pattern) )
    {
        cout << "match!"  << endl;
        for (size_t i = 0; i < result.size(); i ++)
        {
            cout << result[i] << endl;
        }
    } else
    {
        cout << "A table must have at least 1 column." << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

你的最后一个正则表达式有3个捕获组,它们以交替方式分隔 只有1匹配。你正坐在一个循环中打印所有的smatch数组 smatch数组是所有捕获组的大小。

      \s* 
 1    ( \w+ \s+ int )
   |  
 2    ( \w+ \s+ float )
   |  
 3    ( \w+ \s+ char\( \d+ \) )

组0是整场比赛 第1组不匹配,空 第2组不匹配,它是空的 第3组比赛。

您可能想要检查一个组是否匹配 类似于if(result[i].matched){}的东西 或者smatch使用的任何标志。

相关问题