2013-11-02 39 views
0

我正在做我的miniSQL,并试图使用正则表达式来解析用户输入。regex_match()后的冗余空行()

我未能处理'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; 
    } 
} 
+0

看起来它是为所有三个括号表达式记录一个组,但显然只有其中一个匹配,所以它将前两个输出为空格。如果将另一对括号中的\\ s *'后的整个表达式包装在一起,会发生什么?如果你改变顺序,所以带有'char'的组在另外两个之前,那么你会在最后得到两个空行,而不是在中间? –

回答

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使用。

+0

我明白了。谢谢! –