我想在我的 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 脚本中工作。以下是我到目前为止在这个问题上的发现:
https://www.sqlite.org/tclsqlite.html
https://github.com/sei-mi/sqlite3_ar_regexp/blob/master/lib/sqlite3_ar_regexp/extension.rb
http://www.sqlite.org/lang_expr.html#regexp
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/