【问题标题】:How do I get sqlite3 to do regexp in Tcl如何让 sqlite3 在 Tcl 中执行正则表达式
【发布时间】:2016-03-11 05:59:39
【问题描述】:

我想在我的 Tcl 项目中包含正则表达式,但是当我运行我的代码时,我得到了这个错误:

没有这样的功能:REGEXP

我的代码如下所示:

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

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

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

20 行返回自:select * from uniq WHERE input REGEXP '^(.){1}0'(耗时 18 毫秒)

所以 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
         }  

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

【问题讨论】:

    标签: regex sqlite tcl


    【解决方案1】:

    启用正则表达式处理实际上非常简单。您所要做的(假设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
    

    【讨论】:

    • 谢谢!看起来很简单,但我永远不会自己想出来!我还发现,使用“_”的 LIKE 可以处理我使用正则表达式的大部分内容,因此对于其他有此问题的人来说,这可能是一个可行的替代方案。
    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多