将存储在 mysql 字段中的正则表达式字符串用于 Rails 项目

Use regex string stored in mysql field for Rails project

为了清理我的 Rails 项目的代码,我将所有正则表达式字符串移至 MySQL。如何将位于 MySQL 字段中的字符串添加到我的匹配方法中?这是我正在尝试做的一个例子:

foobar = []
regular_ex = StringDb.pluck(:id, :regex) 
# :regex is a column that stores regex strings, ie. '/[a-c]|[1,2,3]/'
regular_ex.each do |exp|
    if foo.match(exp[1])
        foobar << exp[0]

如果我的问题不清楚,请告诉我。 提前致谢!

您可以像这样从字符串创建新的正则表达式

Regexp.new str

或者使用正则表达式插值

%r{#{regex_string}}

这意味着你会做类似的事情

foobar = []
regular_ex = StringDb.pluck(:id, :regex) 
# :regex is a column that stores regex strings, ie. '/[a-c]|[1,2,3]/'
regular_ex.each do |exp|
    if Regexp.new(exp).match("stringToMatch")
        # do something

请注意两点。

  1. 为了使其正常工作,您应该从数据库中的正则表达式中删除开始和结尾的斜线。

存储“[a-c]|[1,2,3]”而不是“/[a-c]|[1,2,3]/”。

  1. 我不太确定您为什么决定将所有正则表达式存储在数据库中,但这听起来不是个好主意。