我如何让sqlite3在Tcl中做正则表达式

How do I get sqlite3 to do regexp in Tcl

我想在我的 Tcl 项目中包含正则表达式,但是当我 运行 我的代码时出现此错误:

no such function: REGEXP

我的代码如下所示:

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

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

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

20 Rows returned from: select * from uniq WHERE input REGEXP '^(.){1}0' (took 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?

所以我得出的结论是,我必须自己编写某种函数才能使其正常工作,但我不知道该函数的外观。它只是将我制作的正则表达式传递给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
         }  

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

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

db function regexp -deterministic {regexp --}

这告诉 SQLite 创建函数,它是确定性的(因为正则表达式匹配最肯定是)并且它应该通过将参数传递给 regexp ---- 停止 REs以 - 开头的问题。

从会话日志中亲自查看:

% 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