我正在做我的 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;
}
}