0

私は miniSQL を実行しており、正規表現を使用してユーザー入力を解析しようとしています。

ケース「create table myTable(c char(20))」の処理に失敗しました。以下に示すように、2 行目と 3 行目は不要です。なぜそれらが結果に表示されるのか疑問に思っています。

これが私のコードです:

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 配列は、すべてのキャプチャ グループのサイズです。

      \s* 
 1    ( \w+ \s+ int )
   |  
 2    ( \w+ \s+ float )
   |  
 3    ( \w+ \s+ char\( \d+ \) )

グループ0は試合全体です。
グループ 1 は一致しませんでした。空です。
グループ 2 は一致しませんでした。空です。
グループ 3 が一致しました。

おそらく、グループが一致したかどうかを確認する必要があります。
if ( result[i].matched) { }
または smatch が使用するフラグのようなもの。

于 2013-11-02T03:58:58.360 に答える