如何让sqlite3在Tcl中执行regexp

时间:2015-12-06 16:40:31

标签: regex sqlite tcl

我想在我的Tcl项目中包含regexp但是当我运行我的代码时出现此错误:

  

没有这样的功能:REGEXP

我的代码如下:

return [brain eval "select * from bad WHERE input REGEXP '^(.){0}_'"]

我可以在数据库中测试这个确切的代码(我使用BD浏览器访问SQLite来浏览数据库)并且它可以正常工作:

select * from uniq WHERE input REGEXP '^(.){1}0'
  

返回20行:select * from uniq WHERE input REGEXP   '^(。){1} 0'(耗时18ms)

因此REGEXP将在浏览器中运行,但不在我的Tcl脚本中。这是我到目前为止在这个问题上发现的:

  1. 其他人在ruby中遇到同样的问题:How to turn on REGEXP in SQLite3 and Rails 3.1?
  2. Somone在iOS中遇到同样的问题,不得不使用cretae_sqlite_function "No such function: REGEXP" in sqlite3 on iOS
  3. 如何在sqlite中编写函数:https://www.sqlite.org/c3ref/create_function.html
  4. 如何在Tcl中为sqlite编写函数: https://www.sqlite.org/tclsqlite.html
  5. 我可能要用ruby编写的函数示例: https://github.com/sei-mi/sqlite3_ar_regexp/blob/master/lib/sqlite3_ar_regexp/extension.rb
  6. 默认情况下未定义REGEXP用户功能: http://www.sqlite.org/lang_expr.html#regexp
  7. REGEXP用户定义函数的PHP示例: How do I use regex in a SQLite query?
  8. 所以我得出的结论是,我必须自己编写某种功能才能使其工作,但我不知道该功能看起来是什么样的。它只是简单地传递我对sqlite3的正则表达式吗?或者是否将正则表达式转换为其他内容然后传递给它?

    该功能看起来像这样吗?

    file mkdir db
    sqlite3 db ./brain/brain.sqlite -create true
    
    db eval { create_function('regexp', 2) do |func, pattern, expression|
                func.result = expression.to_s.match(
                Regexp.new(pattern.to_s, Regexp::IGNORECASE)) ? 1 : 0
             end
             }  
    

    感谢您提供给我的任何帮助或建议!

1 个答案:

答案 0 :(得分:6)

启用正则表达式处理实际上非常简单。您所要做的就是(假设db是您的连接句柄),请使用function method,如下所示:

db function regexp -deterministic {regexp --}

这告诉SQLite创建函数,它是确定性的(正如大多数肯定是正则表达式),并且它应该通过将参数传递给regexp --来工作(--停止开始的RE -造成问题。)

从此会话日志中查看:

% package require sqlite3
3.8.10.2
% sqlite3 db :memory:
% db eval {select 1 where 'abc' regexp 'b'}
no such function: regexp
% db function regexp -deterministic {regexp --}
% db eval {select 1 where 'abc' regexp 'b'}
1