【问题标题】:feed user regex match into database query将用户正则表达式匹配输入数据库查询
【发布时间】:2015-05-12 17:46:19
【问题描述】:
class Database
  include Cinch::Plugin

  DB = SQLite3::Database.new('development.sqlite3')
  match /(select .* from gears where .* like .*)/i 

  def execute(m)
    @db = SQLite3::Database.new('development.sqlite3')
    #m.reply @db.execute("select * from gears where lab like 'Primary'") 
  end
end

IRC 机器人的这一部分。我正在尝试将用户输入的匹配正则表达式直接输入到@db.execute 以便能够执行查询。任何有关不同方式的帮助或建议将不胜感激。

【问题讨论】:

  • 是否有某些原因您不能获取用户提供的字符串并直接使用它?用户输入的示例是什么?
  • 我想使用正则表达式,因为可能有多个输入。一个示例输入是“select * from gears where Lab like 'Primary'”,另一个示例是“select * from gears where RU like 40”。区别在于“。*”所在的正则表达式。如果我在哪里使用字符串,我将不得不为所有查询可能性编码,而不仅仅是填写空白情况。 @Micah
  • 好吧,那应该相当简单。我假设execute(m) 是我们正在研究的方法,其中m 是字符串输入?
  • 是 "m.reply " 是如果输入匹配的正则表达式,则在 irc 通道中返回的内容。

标签: sql ruby regex sqlite cinch


【解决方案1】:

按照这些思路应该可以工作:

def execute(m)
  @db = SQLite3::Database.new('development.sqlite3')
  input = m.input # or however you're getting the input into this function
  regex = /(select .* from gears where .* like .*)/i 
  db_query_string = regex.match(input).to_s
  m.reply @db.execute(db_query_string) 
end

【讨论】:

  • 不走运 :(。“匹配”需要在函数之外调用。如果我把它放在里面它不会识别匹配。
  • @aealvarez3 你的匹配功能对我来说似乎很奇怪。是不是典型的RubyRegex#match函数?
  • 我不是 100% 肯定的,但我想说不是。这是 Cinch 中使用的命令,用于将用户输入匹配到 IRC 聊天室并返回我指定的任何内容。 github.com/cinchrb/cinch
  • 啊!这解释了我的困惑。它来自Cinch,这不是我经常使用的东西。让我做一些研究。
  • @aealvarez3 好的,阅读Cinch match 命令只是一个侦听器,它等待消息与输入匹配,然后使用提供的消息调用execute(m)regex.match 与您的其他 match 函数不同。因此,只要您可以在我提到的点获得输入的消息,我的示例就可以工作。所以问题是:你能在execute(m) 中得到用户输入吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-18
  • 2011-01-31
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多