0

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

我未能处理“创建表 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;
    }
}
4

1 回答 1

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) { }
或任何标志匹配使用的东西。

于 2013-11-02T03:58:58.360 回答