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

标签 regex sqlite 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 脚本中工作。以下是我到目前为止在这个问题上的发现:
  • 其他人在 ruby​​ 中遇到了同样的问题:How to turn on REGEXP in SQLite3 and Rails 3.1?
  • Somone 在 iOS 中也有同样的问题,不得不使用 cretae_sqlite_function "No such function: REGEXP" in sqlite3 on iOS
  • 如何在 sqlite 中编写函数:https://www.sqlite.org/c3ref/create_function.html
  • 如何在 Tcl 中为 sqlite 编写函数:
    https://www.sqlite.org/tclsqlite.html
  • 我可能必须用 ruby​​ 编写的函数示例:
    https://github.com/sei-mi/sqlite3_ar_regexp/blob/master/lib/sqlite3_ar_regexp/extension.rb
  • 默认情况下未定义 REGEXP 用户函数:
    http://www.sqlite.org/lang_expr.html#regexp
  • 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 -- 来工作。 (-- 阻止以 - 开头的 RE 引起问题)。

    从这个 session 日志中你自己看看:

    % 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
    

    关于regex - 我如何让 sqlite3 在 Tcl 中做正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119916/

    相关文章:

    regex - 使用正则表达式确保某些内容包含单独的数字

    sql - 确保 SQLite 表只有一行

    TCL 获取带有某种 -nohang 选项的命令?

    android - sql语句中同一个查询的多个case和order_by?

    tcl - 格式错误的 expr 在 Tcl 中返回空字符串

    linux - 打开愿望而不窃取焦点

    regex - 使用正则表达式匹配组的 Powershell 重命名

    python - 如何为内联有序列表创建正则表达式?

    javascript - 如何将所有 RegEx 捕获组作为单个字符串获取?

    sql-server - 如何在SQL Server数据库的多个表中查找匹配的列?