C++ regex_match()之后的冗余空行

C++ regex_match()之后的冗余空行,c++,regex,C++,Regex,我正在使用miniSQL并尝试使用正则表达式来解析用户输入 我无法处理“创建表myTable(c char(20))”的情况。如下图所示,第二行和第三行是不需要的。我只是想知道为什么他们会出现在结果中。 这是我的密码: void onCreateTable(const smatch& cmd); int main() { std::string cmd = " create table a(c char(20))"; regex pattern; smatch

我正在使用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;
    }
}
void onCreateTable(const smatch&cmd);
int main()
{
std::string cmd=“创建表a(c字符(20))”;
正则表达式模式;
smatch结果;
pattern=regex(“\\s*create\\s+table\\s+(\\w+)\\s*\\(.*\\)\\s*”,regex::icase);
if(正则表达式匹配(cmd、result、pattern))
{
onCreateTable(结果);
}
int x;cin>>x;
返回0;
}
void onCreateTable(const smatch&cmd)
{

cout您的上一个正则表达式有3个捕获组,以交替方式分隔。
只有1个匹配。您正在循环打印所有smatch阵列。
smatch阵列是所有捕获组的大小

      \s* 
 1    ( \w+ \s+ int )
   |  
 2    ( \w+ \s+ float )
   |  
 3    ( \w+ \s+ char\( \d+ \) )
第0组为整场比赛。
第1组不匹配,为空。
第2组不匹配,为空。
第三组比赛

您可能需要检查组是否匹配。
类似于if(
result[i]。matched
){}

或者smatch使用的任何标志。

看起来像是为所有三个括号中的表达式记录一个组,但显然只有一个表达式实际匹配,所以它将前两个作为空白打印。如果将整个表达式包装在另一对括号中,会发生什么情况?如果更改顺序,使OUP与 char < /C> >在另两个之前,然后在结尾处得到两条空行,而不是在中间?