正则表达式与 c++ 不匹配

Regex not matching c++

本文关键字:不匹配 c++ 正则表达式      更新时间:2023-10-16

我有这个字符串要测试:

"CPF char,
Nome char [80],
Idade int,
Salario double,
Sexo char,
Tem_Filhos bool,"

或者简单地说:

string testStatement("CPF char,nNome char [80],nIdade int,nSalario double,nSexo char,nTem_Filhos bool,");

这是我的正则表达式:

regex createTableInside("(?:[ \n\t]*)(\w*)(?:[ \n\t]+)(?:(?:(char)[ \n\t]*\[[ \n\t]*(\d*)[ \t\n]*\])|(char)|(int)|(double)|(bool)|(bloob))(?:[ \n\t]*)(,)");

当我做一个regex_search时,它会找到所有内容:

while(regex_search(testStatement, check, createTableInside))
{
    for(index = 1; index < check.size(); index++)
    {
        if(check.str(index).compare("") == 0) continue;
        cout << """ << check.str(index) << """ << endl;
    }
    aux = check.suffix();
}

输出:

"CPF"
"char"
","
"Nome"
"char"
"80"
","
"Idade"
"int"
","
"Salario"
"double"
","
"Sexo"
"char"
","
"Tem_Filhos"
"bool"
","

但是当我做regex_match时,check.size()总是返回0

我已经在这里测试了我的正则表达式:https://www.debuggex.com/,它可以工作。

我也尝试了match_any常量:

regex_match(testStatement, check, createTableInside, match_any);

怎么了?

谢谢。

来自文档(std::regex_search 来自 cppreference.com):

std::regex_search将成功匹配给定序列的任何子序列,而std::regex_match只有在正则表达式匹配整个序列时才返回 true。

您可能需要检查std::match_results,以检查std::regex_match()在哪个点未能匹配完整的序列(请参阅std::match_results::suffix()std::match_results::prefix()成员)。