我在sqlite3中使用了C,我想添加对REGEXP运算符的支持。默认情况下,用户定义的函数regexp()不存在,并且调用REGEXP通常会导致错误(根据SQLite页面)。

  • 如何添加regexp函数以支持REGEXP?大概我将通过sqlite3_create_function调用来做到这一点,但是我不知道应用程序定义的regexp()会是什么样。
  • 我可以使用regex.h中的sqlite3_create_function中的函数吗?如何使用?我传递给SQLite的任何函数都必须采用sqlite3_context *类型的三个参数,即int,sqlite3_value **类型。但是,SQLite文档似乎并未解释这些参数的含义。
  • 是否有C regexp()函数的示例代码?

  • 使用Google或SQLite页面在此方面我找不到太多的东西。

    最佳答案

    您也可以尝试以下操作:

    #include <regex.h>
    

    ...
    void sqlite_regexp(sqlite3_context* context, int argc, sqlite3_value** values) {
        int ret;
        regex_t regex;
        char* reg = (char*)sqlite3_value_text(values[0]);
        char* text = (char*)sqlite3_value_text(values[1]);
    
        if ( argc != 2 || reg == 0 || text == 0) {
            sqlite3_result_error(context, "SQL function regexp() called with invalid arguments.\n", -1);
            return;
        }
    
        ret = regcomp(&regex, reg, REG_EXTENDED | REG_NOSUB);
        if ( ret != 0 ) {
            sqlite3_result_error(context, "error compiling regular expression", -1);
            return;
        }
    
        ret = regexec(&regex, text , 0, NULL, 0);
        regfree(&regex);
    
        sqlite3_result_int(context, (ret != REG_NOMATCH));
    }
    

    ...
    sqlite3_create_function(*db, "regexp", 2, SQLITE_ANY,0, &sqlite_regexp,0,0)
    

    10-06 07:17
    查看更多